Nested output with related models - ruby-on-rails

I have a model Category and a model Weblink. Category has_many Weblink and Weblink belongs_to Category. Now I want to show all categories in a view and within a category all weblinks belonging to that category, something link this:
<ul>
<% #categories.each do |category| %>
<%= category.category_name %>
<% #weblinks.each do |weblink| %>
<%= weblink.category_name link_to weblink.link_name, weblink.link_url %>
<% end %>
<% end %>
In the controller I have:
#categories = Category.all
#weblinks = Weblink.all
This shows every category and within every category all weblinks, instead of just the ones which belong to the specific category. How can I fix this?

Your view code should look like this
<% #categories.each do |category| %>
<%= category.name >
<% category.weblinks.each do |weblink| %>
<%= link_to weblink.name, weblink.link_url %>
<% end -%>
<% end -%>
It your controller, when querying for all the categories you should also include the weblinks model, something like this:
#categories = Category.all(:include => :weblinks)

Scope the inner loop to the outer category using the macro you get with has_many:
<% #categories.each do |category| %>
<%= category.category_name %>
<% category.weblinks.each do |weblink| %>
<%= link_to weblink.link_name, weblink.link_url %>
<% end %>
<% end %>

Related

rails referencing arrays created by the group_by function

This code causes ActionController to return undefined method `name' for # How do I print the category name
<h2>Categories</h2>
<%= #categories.group_by(&:parent_id).each do |category| %>
<%= category.name %>
<% end %>
I mean, that the :parent_id is an attribute of Category model and #categories is a collection of ::ActiveRecord_Relation class. Let you try:
<h2>Categories</h2>
<%= #categories.group(:parent_id).each do |category| %>
<%= category.name %>
<% end %>
Consider using <%= debug #categories.group_by(&:parent_id) %> so that you can inspect the data structure
I believe you want to pass two arguments to the each block, one for the parent and one for the categories associated with it
<h2>Categories</h2>
<% #categories.group_by(:parent).each do |parent, categories| %>
<%= parent.name %>
<ul>
<% categories.sort_by(&:name).each do |category| %>
<li><%= category.name %></li>
<% end %>
</ul>
<% end %>
Above is based on my assumptions about your data model which could be totally incorrect?

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.

Rails: Displaying a nested list

I have a property listing site with the following relationship structure
Region has_many :cities
City has_many :investor_cities
City has_many :investors through: :investor_cities
Investor has_many :investor_cities
Investor has_many :cities through: :investor_cities
An investor_city records cities that an investor prefers to buy in. It will be used to match properties with investors.
In the show view for an investor, I want to show cities by region that they are interested in.
In the controller
#regions = Region.all
In the view
<% #regions.each do |r| %>
<p><%= r.name %></p>
<ul>
<% r.cities.each do |c| %>
<% #inv_cty = InvestorCity.find_by_city_id_and_investor_id(c.id, #investor.id) %>
<% if #inv_city %>
<%= #inv_city.city.name %>
<% end %>
<% end %>
</ul>
<% end %>
However no investor_cities are rendered (despite there being two in the database).
I also tried this:
r.cities.investor_cities.each do...
But got this error.
undefined method `investor_cities' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_City:0x007fb47e09b4d0>
Am at a bit of a loss so any ideas would be great. Thanks.
Edit - the below has worked. I would love to know how to do it a bit cleaner however. Thanks
<% #regions.each do |r| %>
<p><%= r.name %></p>
<ul>
<% r.cities.each do |c| %>
<% c.investor_cities.each do |ic| %>
<% if ic.investor_id == #investor.id %>
<li><%= ic.city.name %> <%= ic.investor.id %></li>
<% end %>
<% end %>
<% end %>
</ul>
<% end %>
Instead of use r.cities.investor_cities.each do...,
try using r.cities.select('investor_cities').where(investor_id: #investor.id).each do ...

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 ...

rails: display unique records in each loop

I have a product display page which is displaying all products on website. Here I want to filter products as per their Owner. As a start, i am displaying owner names on page using each loop:
<% #products.each do |p| %>
<%= link_to p.user.profile.first_name, store_index_path %>
<% end %>
But as owner has multiple products, his name gets displayed multiple times. How to show the name only once?
In simple way you can do like this:
<% #products.map(&:user).uniq.each do |u| %>
<%= link_to u.profile.first_name, store_index_path %>
<% end %>
You can use group_by to create a hash of User => [Products]. Then, you iterate through the unique set of Users, display the information about that owner, and then display each product for that User.
<% products_by_owner = #product.group_by(&:user) %>
<% products_by_owner.keys.each do |user| %>
<%= link_to p.user.profile.first_name, store_index_path %>
<% products_by_owner[user].each do |product| %>
<%= link_to product.name, store_index_path %>
<% end %>
<% end %>
You can use group_by to create a hash with the users as keys and arrays of products as values:
# Eager loading of users will prevent multiple database hits.
# Using find:
#products = Product.find(:all, :include => :user).group_by(&:user)
# using relations:
#products = Product.where(:some_condition => 'etc').includes(:user).group_by(&:user)
In the view:
<% #products.each do |user, user_products| %>
<%= link_to p.user.profile.first_name, store_index_path %>
<% user_products.each do |product| %>
...
<% end %>
<% end %>

Resources