Ruby view nested element inside index - ruby-on-rails

I have two models with the following relationship
Event
has_many :comments
Comment
belongs_to :event
What I would like to do is in Post.index is to show elements of Post but also comment.descriptions.
Here a controller
def index
#events = Event.all(:include => :comments)
...
Here how its build
def new
#event = Event.new
#event.comments.build
end
But i am not to sure how to show in post.index.html comments.description. I try this but it fails
<% #events.each do |event| %>
<% if event.comments.count <= 1 %>
<%= event.description%>
<% end %>
<% end %>
The error is undefined method (description)

You just need to loop through the comments for each event while you are looping through the events.
<% #events.each do |event| %>
<% event.comments.each do |comment| %>
<%= comment.description %>
<% end %>
<% end %>

Related

How can I show all models in one index page and order them by "created_at DESC"?

I have a Posts Model, and a Projects Model. I want to render both of these on one index page and order them by created_at DESC. How can I do this? Thanks in advance...
Separately?
<% Post.order('created_at DESC').each do |post| %>
#do things
<% end %>
<% Project.order('created_at DESC').each do |project| %>
#do things
<% end %>
Together?
<% (Post.all + Project.all).sort_by{|item| -item.created_at}.each do |item| %>
<% if item.is_a? Post %>
<%= render 'post_partial', post: item %>
<% elsif item.is_a? Project %>
<%= render 'project_partial', project: item %>
<% end %>
<% end %>
Then create a partial for both objects, and use your attributes as needed!

Ruby on Rails: why does the content of each child print out when I iterate over them?

I have the following models:
class Question < ActiveRecord::Base
has_many :ratings
end
class Rating < ActiveRecord::Base
belongs_to :question
end
I also have the following code in the question's show.html.erb file:
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= #question.name %>
</p>
<% if #ratings.blank? %>
<p>There are no ratings for this question.</p>
<% else %>
<ul>
<%= #ratings.each do |rating| %>
<li>
<%= rating.name %>
<%= link_to "Show", rating %>
</li>
<% end %>
</ul>
<% end %>
<%= link_to 'Edit', edit_question_path(#question) %> |
<%= link_to 'Back', questions_path %>
The relevant questions_controller.rb entry is as follows:
def show
#question = Question.find(params[:id])
#ratings = Rating.where(question_id: #question.id)
respond_with(#question)
end
I can't for the life of me see why the output contains the contents of the child objects, as well as just the unordered list items that I've created in my iteration. Any thoughts?
Try to remove the = in this line: <%= #ratings.each do |rating| %>
Use - but = in your each loop
- #pages.each do |x|
p = x.id
p = x.xx
This is what you want.
Also, I recommend you to use slim as a replacement of erb.

DRY ruby on rails loops

I am trying to loop through my users and sum an attribute act_points from associated post_activites and then assign and save it to my users table attribute total_points. The code below works for me but it doesn't follow DRY.
<% #users.order("total_points desc").each do |u| %>
<p><% u.total_points = u.post_activities.sum(:act_points).round(2) %> </p>
<% u.total_points %>
<% u.save %>
<%end%>
<% #users.order("total_points desc").each do |u| %>
<p><% u.total_points = u.post_activities.sum(:act_points).round(2) %> </p>
<%= u.total_points %>
<%end%>
Any suggestions on how to combine these loops or shorten them?
You can refactore your code in this way:
# user.rb
def actual_points
post_activities.sum(:act_points).round(2)
end
def update_total_points
update(total_points: actual_points)
end
# in controller (change index to your method)
def index
#users = User.order("total_points desc")
#users.find_each do |user|
user.update_total_points
end
end
# view
<% #users.each do |u| %>
<%= u.total_points %>
<%end%>

Best way to define global objects in Ruby on Rails

I have an app that has two models Category and Product
Products belong to categories.
I have created a navbar dropdown that requires an #category and #product object to be available across the entire app (the navbar is shown on every page of the application.)
What I can't work out is the best place to put these basic definitions without defining them multiple times in every page definition.
I need to define the following:
#category = Category.all
#products = #category.products.all
The navbar loop will then look something like this.
<% #category.each do |c| %>
<%= c.name %>
<% #products.each do |p| %>
<% link_to product_path(p) do %>
<%= p.name %>
<% end %>
<% end %>
<% end %>
I am a bit of a rails newbie so I am sure there are some errors in here but any help would be much appreciated!
If you need them in every single page of app, you can set them in ApplicationController's before_filter:
class ApplicationController
before_filter :get_categories
# ...
private
def get_categories
#categories = Category.includes(:products)
end
end
then, you can write in your view:
<% #categories.each do |category| %>
<%= category.name %>
<% category.products.each do |product| %>
<%= link_to p.name, p %>
<% end %>
<% end %>
I also fixed some other errors and convention incompatibilities.
The following code is incorrect.
#category = Category.all
#products = #category.products.all
This code assigns to #categories all the categories, then it attempts to fetch the products. It will not work, unless you have defined a products class method in the Category model. But I don't think so, otherwise you will just have to call Product.all.
Moreover, in the code below, you are trying to display the list of products per category, which definitely don't work with the two assignments before. According to what you are trying to achieve, you can't pre-assign the #products, because you want the products for a specific category.
Let's inline everything into the code.
<% Category.all.each do |category| %>
<%= category.name %>
<% category.products.each do |product| %>
<%= link_to product_path(product) do %>
<%= product.name %>
<% end %>
<% end %>
<% end %>
Next step is to make the code a little bit more performant, giving you need it everywhere.
<% Category.select(:id, :name).each do |category| %>
<%= category.name %>
<% category.products.select(:id, :name).each do |product| %>
<%= link_to product_path(product) do %>
<%= product.name %>
<% end %>
<% end %>
<% end %>
You could use pluck, but it will return an array and it will require a little bit more manipulation. However, it's way more performant.
<% Category.pluck(:id, :name).each do |category_id, category_name| %>
<%= category_name %>
<% Product.where(category_id: category_id).pluck(:id, :name).each do |product_id, product_name| %>
<%= link_to product_name, product_path(id: product_id) %>
<% end %>
<% end %>
It's not a good idea to chain all those methods inside a view, let's extract some code into the model.
class Category
def self.simple_listing
order(:name).pluck(:id, :name)
end
end
class Product
def self.simple_category_listing(category_id)
where(category_id: category_id).order(:name).pluck(:id, :name)
end
end
<% Category.simple_listing.each do |category_id, category_name| %>
<%= category_name %>
<% Product.simple_category_listing(category_id).each do |product_id, product_name| %>
<%= link_to product_name, product_path(id: product_id) %>
<% end %>
<% end %>
You can leave all this code into the view, or extract it into a partial. You don't even need to add a controller before filter, or make it "global". The code is self-contained, does not pollute the name space with instance variables, and it can easily be placed whenever you need it.

how to use order by in rails model

Consider I have a index controller which will display all category and sub category
My index controller has
#categories = Category.where(status: true)
category.rb
has_many :sub_categories
here is my sub_category
sub_category.rb
belongs_to :category
In my view I have
<% #categories.each do |category| %>
<%= category.name %>
<% category.sub_categories.each do |sub_category| %>
<%= sub_category.name %>
<% end %>
<% end %>
My sub_category has status(true, false) I need to display only the sub_category with the status as true
How can I do this.
By using where, i.e. category.sub_categories.where(status: true):
<% #categories.each do |category| %>
<%= category.name %>
<% category.sub_categories.where(status: true).each do |sub_category| %>
<%= sub_category.name %>
<% end %>
<% end %>
Or even better to return only what's required, just select the #categories that have subcategories with status = true.
For this update your controller's action code where you have #categories defined:
# controller
#categories = Category.includes(:sub_categories).where('sub_categories.status = ?', true)
Then in your view:
<% #categories.each do |category| %>
<%= category.name %>
<% category.sub_categories.each do |sub_category| %>
<%= sub_category.name %>
<% end %>
<% end %>
I would recommend to use scope in your app. In SubCategory model add scope :active, where(active: true) and then use category.sub_categories.active.each ...

Resources