group_by posts by day and then date with different div - ruby

I have the following in my index action of posts controller:
#posts = Post.all.order("created_at DESC")
In my view like:
<% #posts.each do |post| %>
<%= post.title %>
<% end %>
I want to group the posts by day and then the date like the following:
Tuesday (date)
Sports
World
Politics
Monday (date)
Sports
Catering
I just want to have the day and date in separate div's:
(<div>
<%= day %>
</div>
<div>
<%= date %>
</div>)
I am using PostgreSQL.
UPDATE
create.js.erb
$("#post_table").html("<%= escape_javascript(render('posts/post')) %>")
$modal.modal("hide");
posts_controller:
before_action :all_posts, only: [:index, :new, :create]
def create
#post = Post.new(post_params)
#post.user_id = current_user.id
respond_to do |format|
if #post.save
format.html { redirect_to root_path }
format.js
flash[:notice] = "Successfully created post."
else
format.html { render action: 'new' }
format.js
end
end
end
private
def all_posts
#posts = Post.all.order("created_at DESC")
#post_groups=#posts.group_by{|post| [post.created_at.wday,post.created_at.to_date]}
end
index.html.erb
<% #post_groups.each do |group,posts| %>
<% day = group[1].strftime("%A") %>
<% date = group[1].strftime("#{group[1].day.ordinalize}" " %B " " %Y") %>
<div class="sort_by_date">
<span class="sort_by_post_day">
<%= day %>
</span>
<span class="sort_by_post_ordinals">
<%= date %>
</span>
</div>
<div id="post_table">
<%= render 'post', posts: #posts %>
</div>
<% end %>
Update is working fine, but whenever create a new post the refresh part is not working. it refresh but I could see the new post after I reload my website.
Thanks

controller
#post_groups=Post.order('created_at DESC').group_by{|post| [post.created_at.wday,post.created_at.to_date]}
View
<% #post_groups.each do |group,posts| %>
<%day=group[1].strftime("%A")%>
<%date=group[1].to_s%>
<div>
<%=day%>
</div>
<div>
<%=date%>
</div>
<br>
<%posts.each do |post|%>
<div><%=post.title%></div>
<%end%>
<hr>
<% end %>
In here I grouped all the posts by weekday and then group them with date.
This will return the hash of all the grouped data. hash key will be an array of format
[weekday,date] and value for this key will be an array of Posts which comes to this group and i am showing them in view according.
You can fiddle around view to change the styling according to your requirement.

Related

How to update feed using ajax in Rails 4.0

I am trying to create an ajax functionality for a sample app of michael heart book . I created a feed model controller which is micropost in hear book . I am trying to use ajax like post feed method . But I am getting some error . I am attaching my code below take a look and help me .
#feeds_controller.erb
class FeedsController < ApplicationController
before_action :authenticate_user! ,only: [:create, :destroy]
def create
#feed = current_user.feeds.build(feed_params)
if #feed.save
flash[:success] = "Micropost created!"
#redirect_to root_url
respond_to do |format|
format.html { redirect_to root_url }
format.js
else
#feed_items = []
render 'static_pages/home'
end
end
def destroy
end
private
def feed_params
params.require(:feed).permit(:content)
end
end
And my home page is rendering some partials Here is the code :
#static_pages/home.html.erb
<% if user_signed_in? %>
<div class="row">
<aside class="col-md-4">
<section class="user_info">
<%= render 'shared/user_info' %>
</section>
<section class="stats">
<%= render 'shared/stats' %>
</section>
</aside>
<div class="col-md-8">
<h3>Micropost Feed</h3>
<section class="micropost_form">
<%= render 'shared/feed_form' %>
</section>
<%= render 'shared/feed' %>
</div>
</div>
<% else %>
<% end %>
Here are two codes Everything work perfectly but when I am trying to add ajax I get the error which is :
Rendered shared/_feed.html.erb (3.1ms)
Rendered feeds/create.js.erb (6.0ms)
Completed 500 Internal Server Error in 73ms (ActiveRecord: 44.4ms)
NoMethodError (undefined method `any?' for nil:NilClass):
app/views/shared/_feed.html.erb:1:in `_app_views_shared__feed_html_erb___516512175__638262078'
app/views/feeds/create.js.erb:1:in `_app_views_feeds_create_js_erb___967625174__637838198'
app/controllers/feeds_controller.rb:9:in `create'
To execute ajax on create method I added these files unders feeds views file name is create.js.erb
$("#feed_add").html("<%= escape_javascript(render partial: "shared/feed") %>");
And form file is under shared view file with name _feed_form.html.erb
<%= form_for(#feed,:remote => true) do |f| %>
<div id="feed_add">
<%= f.text_area :content, placeholder: "Compose new feed..." %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>
#_feed.html.erb
<% if #feed_items.any? %>
<ol class="microposts">
<%= render #feed_items %>
</ol>
<%= will_paginate #feed_items %>
<% end %>
So tell me how can I add feed and without refreshing how can I show feed using partial In this code .
Here you simply need to render one thing that is feed for that in micheal heart book you simply add this line of code inside your create ajax file here is the code :
$(".microposts").prepend('<%= j render #feed %>');
Here you can get the result what you want .

Can't Edit Item Error NoMethodError in Items#edit

I have an Item Model. Its for a retail store.
When im on an item view. Lets say for item id 11. Then i click on edit button. I receive the following error
Anyone have any clues? Any help would be greatly appreciated.
NoMethodError in Items#edit
undefined method `errors' for nil:NilClas
<% if #user.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(#user.errors.count, "error") %>.
</div>
<ul>
Below is where my edit button is in Item View
<!-- right column -->
<div class="col-lg-6 col-md-6 col-sm-5">
<div class = "itemtitle"><%= #item.title %> </div>
<div class = "price">$<%= #item.price %> </div>
<%= link_to "Edit Items", edit_item_path(#item) %>
<div class="productFilter productFilterLook2">
<div class="filterBox">
<select>
<option value="strawberries" selected>Quantity</option>
</select>
</div>
Here is my Items controller.
class ItemsController < ApplicationController
def index
#items = Item.paginate(page: params[:page])
end
def new
#item = Item.new
end
def edit
#item = Item.find(params[:id])
end
def show
#item = Item.find(params[:id])
end
def update
if #item.update(pin_params)
redirect_to #item, notice: 'Item was successfully updated.'
else
render action: 'edit'
end
end
def create
#item = current_user.items.build(item_params)
if #item.save
redirect_to #item
flash[:success] = "You have created a new item"
else
flash[:danger] = "Your item didn't save"
render "new"
end
end
def destroy
#item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: 'Item was successfully deleted' }
format.json { head :no_content }
end
end
private
def item_params
params.require(:item).permit(:title, :price, :description, :image)
end
end
_error_messages.html.erb
<% if #user.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(#user.errors.count, "error") %>.
</div>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
You don't define #user in your edit action.
Probably somewhere in the template you render for the edit action you ask for #user.errors.any?. Either disable this part or modify to something like #item.errors.any? etc.

Display data according to text field value using Rails 3

I have a issue.I want to fetch data from data base according to text field value.This text field will take two types of value.First one is simple number(e.g-123456789) and second one is like this(e.g-123456789/1).The simple number is present in DB for one table.In the second one number after "/" (i.e-1) is another table's id which is associated with first table.Then my aim is when user will give the input "123456789" the data will fetch according to this number by searching and when user will give the input "123456789/1" first it will split the number and values will be fetched according to both number and id (i.e-123456789 and 1) from the both table.
Here i am explaining some of my code below.
homes/hcsy_html.erb
<% if current_admin %>
<div class="header">
<div class="navbar-header">Swargadwar, Puri Municipality,govt of odisha</div>
<div class="nav navbar-top-links navbar-right">
<div class="image"></div>
</div>
<div class="name-div">
</div>
</div>
<div class="menu-div">
<div id="leftsidebtn">
<ul>
<li>Create User</li>
<li>Scan Report</li>
<li>View and Payment Report
<ul>
<li>HCSY</li>
</ul>
</li>
<li>Payment Validate</li>
<li>Log Out</li>
</ul>
</div>
</div>
<div class="content-div">
Logged in as:<%= current_admin.email %>
<center><h1>HARICHANDRA SAHAYATA YOJANA SLIP</h1></center>
<%= form_for :hcsy,:url => {:action =>'scan_hcsy' } do |f| %>
<%= f.text_field :reciept,placeholder:"Get your scan code",:onchange => 'this.form.submit();' %>
<% end %>
<% if params[:id] %>
<center><h1>HARICHANDRA SAHAYATA YOJANA SLIP</h1></center>
Receipt No :<%= #hcsys.Receipt_No %>
<div class="left-content">
<p>Deceased Name :</p> <%= #hcsys.Deceased_Name %>
<p>Beneficary name :</p> <%= #hcsys.Beneficiary_Name %>
<p>Relation with Deceased :</p> <%= #hcsys.Beneficiary_Rel_With_Decease %>
<p>Address :</p> <%= #hcsys.Address %>
<p>Police station :</p> <%= #hcsys.PoliceStation %>
<p>Mobile No :</p> <%= #hcsys.Mobile_No %>
<p>Occupation :</p> <%= #hcsys.Occupation %>
<p>Brahmin :</p> <%= #hcsys.Brahmin %>
<p>Amount Required :</p> <%= #hcsys.Amount_Required %>
<p>Has He/She recieved any assistance erlier from this fund :</p> <%= #hcsys.Recieved_Fund_Earlier %>
</div>
<div class="right-content">
<p>BPL :</p> <%= #hcsys.BPL %>
<p>Govt. Service :</p> <%= #hcsys.Govt_Service %>
<p>Business :</p> <%= #hcsys.Business %>
<p>Land of property :</p> <%= #hcsys.Land_Property %>
<p>Other :</p> <%= #hcsys.Others %>
</div>
<% end %>
</div>
<% end %>
controller/homes_controller.rb
class HomesController < ApplicationController
def index
end
def registration
#user=User.new
end
def usersave
#admin=Admin.find(params[:id])
#user=User.new(params[:user])
#user.admin_id=#admin.id
if #user.save
flash[:notice]="User has created successfully"
flash[:color]="valid"
redirect_to :action => "index"
else
flash[:alert]="User could not created"
flash[:color]="invalid"
render 'registration'
end
end
def hcsy_reg
#hcsy=THcsy.new
end
def create_reg
#hcsy=THcsy.new(params[:hcsy])
if #hcsy.save
flash[:notice]="Data has saved successfully"
flash[:color]="valid"
redirect_to :action => "hcsy_details",:id1 => params[:id],:id2 => #hcsy.id
else
flash[:alert]="Data could not saved successfully"
flash[:color]="invalid"
render 'hcsy_reg'
end
end
def scan_hcsy
#hcsy=THcsy.find_by_Receipt_No(params[:hcsy][:reciept])
if #hcsy
flash[:notice]="Check the record"
flash[:color]="valid"
redirect_to :action => 'hcsy',:id => #hcsy.id
else
flash[:alert]="Receipt number could not found"
flash[:color]="invalid"
render 'hcsy'
end
end
def hcsy
if params[:id]
#hcsys=THcsy.find(params[:id])
end
end
def scanrecord
#hcsy=THcsy.find(params[:id])
end
def hcsy_deatils
#t_hcsy=THcsyFundTypeMaster.new
end
def create_details
#t_hcsy=THcsyFundTypeMaster.new(params[:t_hcsy])
if #t_hcsy.save
flash[:notice]="Check the record"
flash[:color]="valid"
redirect_to :action => 'hcsy_details_master',:id1 => params[:id1] ,:id2 => params[:id2] , :id3 => #t_hcsy.HCSY_Fund_Type_ID
else
flash[:alert]="Receipt number could not found"
flash[:color]="invalid"
render 'hcsy_deatils'
end
end
def hcsy_details_master
#t_hcsy_master=THcsyDetails.new
end
def create_details1
#admin=Admin.find(params[:id1])
#hcsy=THcsy.find(params[:id2])
#t_hcsy=THcsyFundTypeMaster.find_by_HCSY_Fund_Type_ID(params[:id3])
#t_hcsy_master=THcsyDetails.new(params[:t_hcsy_master])
#t_hcsy_master.Created_By=#admin.id
#t_hcsy_master.HCSY_ID=#hcsy.id
#t_hcsy_master.HCSY_Fund_Type_ID=#t_hcsy.HCSY_Fund_Type_ID
if #t_hcsy_master.save
flash[:notice]="Record has created"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="Record could not create"
flash[:color]="invalid"
render 'hcsy_details_master'
end
end
end
Here i have done for simple number please help me to fetch data from both table by the second input number(i.e-123456789/1).For this all operations are executing inside "scan_hcsy" method.Atleast help me to split the number(i.e-123456789/1) to 123456789 and 1 so that i can fetch data according to this number and id.
You can split the string, which results into an Array:
"12345678/1".split('/')
=> ["12345678", "1"]
In your case:
splitted = params[:hcsy][:reciept].split('/')
hcys = splitted[0]
table_id = splitted[1]

Only Display Current Month Data

I have created a functioning e-commerce platform where Members can buy songs and my Index page organizes the data by Month. Everything works fine, But now I would like to strictly display the information for the current month. (In Our Case JUNE).
Currently I am able to list every month's data, but this can become a problem to display when million of songs are being bought throughout the year.
How Can I Only display the current Months Data?
CONTROLLER
def index
#orders = Order.find(:all, :order => 'order_date, id')
end
VIEW
###How can i Only Display Current Month?
<% #orders.sort.group_by { |order| order.order_date.beginning_of_month }.each do |month, orders| %>
<h3><%= month.strftime('%B') %> </h3>
<% orders.group_by { |order| order.song.album.artist }.each do |artist, orders| %>
<h4><%= artist.name %> </h4>
<% orders.group_by { |order| order.song.album }.each do |album, orders| %>
<h5><%= album.name %> </h5>
<% orders.group_by { |order| order.song }.each do |song, orders| %>
<p>(<%= orders.count %>) <%= song.title %> </p>
<p><%= song.price %> </p>
<% end %>
<% end %>
<% end %>
<% end %>
Something like this perhaps? (in your controller)
#orders = Orders.where('created_at < ? and created_at > ?', Time.now.end_of_month, Time.now.beginning_of_month)

Bring code from view into a popup in Rails

I want to bring this code from my view html into a popup when a link is clicked
Is that possible in Ruby on Rails? I already have the pop up working but I'm wondering about the code to show just the comments:
<div class = "comments"><% if post.comments.exists? %>
<% post.comments.each do |comment| %>
<%= image_tag("http://www.gravatar.com/someavatarlink %) <!-- Retrieves Gravatar -->
<%= link_to comment.user.name, comment.user %>
<span class="timestamp"><%= time_ago_in_words(comment.created_at) %> ago</span>
<span class="content2"><%= comment.comment_content %></span>
<% end %>
<% end %></div>
Added Ajax call to _comment_form.html.erb
<%= link_to "Link", comment, :remote => true %>
Comments
<% end %></div></div>
<div id ="modal" class = "comments"><% if post.comments.exists? %>
<% post.comments.each do |comment| %>
<%= link_to comment.user.name, comment.user %>
<span class="timestamp"><%= time_ago_in_words(comment.created_at) %> ago</span>
<span class="content2"><%= comment.comment_content %></span>
<% end %>
<% end %></div>
Added def show into comments controller
class CommentsController < ApplicationController
def new
#post = post.new(params[:post])
end
def show
#comment = Comment.find(params[:id])
respond_to do |format|
format.js
end
def create
#post = post.find(params[:micropost_id])
#comment = Comment.new(params[:comment])
#comment.post = #post
#comment.user = current_user
if #comment.save
redirect_to(:back)
else
render 'shared/_comment_form'
end
end
end
Created show.erb.js and put it into 'comments' and 'shared' folders
$("#popup").html('<%= escape_javascript(render "comments") %>');
Then finally wrote my partial which is in comments/_comment.html.erb
<% if post.comments.exists? %>
<% post.comments.each do |comment| %>
<%= link_to comment.user.name, comment.user %>
<span class="timestamp"><%= time_ago_in_words(comment.created_at) %> ago</span>
<span class="content2"><%= comment.comment_content %></span>
<% end %>
<% end %>
1. Ajax call
To retrieve the data you use an Ajax call.
<%= link_to "Link", comment, :remote => true %>
Rails will evaluate these requests and will look for a .js view first (it will use .html if it does not exist).
Make also sure that the controller accepts requests to .js like
def show
#comment = Comment.find(params[:id])
respond_to do |format|
format.js
end
end
2. write js view
Add a show.erb.js view to your Comments . This is a JavaScript file with ERB evaluation.
In this template use your js popup code and tell it to fill a div with your html code like so:
$("#popup").html('<%= escape_javascript(render #comment) %>');
This will render the comment. The only thing we need then is a partial to render the html of the comment.
3. write partial for html
Write a partial for the view part you want to have in the popup. This can then be used in a normal html view or the js view. To make it work with the code above call it _comment.html.erb
To know more about partials you can check the guides here:
http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

Resources