rails referencing arrays created by the group_by function - ruby-on-rails

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?

Related

Is a cache available for all identical queries in a rails view?

In my index I call
<% Shoes.roots.each do |shoe| %>
<%= link_to shoe.shoe_name, shoe %>
<% end %>
I have a some html organizing the page and later call:
<% Shoe.roots.each do |shoe| %>
<%= link_to shoe.shoe_name, shoe %>
<%= shoe.shoe_size %>
<% end %>
To provide some links and shoe sizes.
I'm using rack-mini-profiler and it shows me that I am not doing two separate queries. If I cache the top .each do:
<% Shoes.roots.each do |shoe| %>
<% cache(shoe) do %>
<%= link_to shoe.shoe_name, shoe %>
<% end %>
<% end %>
Is the bottom one also cached even though I don't use shoe.shoe_size in the top .each do? Would it work the opposite way?
Rails does cache SQL queries. If the query is identical within the same request, it will not execute the same request again.
You should consider assigning your shoes to an instance variable in the controller:
#roots = Shoe.roots
and then in the views access that variable
<% #roots.each do |shoe| %>
<%= link_to shoe.shoe_name, shoe %>
<% end %>
<% #roots.each do |shoe| %>
<%= link_to shoe.shoe_name, shoe %>
<%= shoe.shoe_size %>
<% 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.

Only show attributes that are present in Rails

In my show view I have a few attributes that aren't required to be filled in by the user. In my show view I can easily create a conditional like so:
<% if #user.occupation.present? %>
<p><%= #user.occupation %></p>
<% end %>
But if I have 3 or more of these optional attributes, creating multiple conditionals for each of them can become very tedious. I thought of doing something like this but it turns out that the method attribute is private:
<% #user.attributes.map do |attribute, name| %>
<% if #user.attributes.present? %>
<p><b><%= name %>:</b> <%= #user.attribute %></p>
<% end %>
<% end %>
For security reasons I'm not necessarily trying to change the attribute method from being private but more so just looking for a way to list attributes of my model that have been filled in.
<% #user.attributes.each do |key, value| %>
<% if value.present? %>
<p><b><%= key %>:</b> <%= value %></p>
<% end %>
<% end %>

How do I separate elements by their type with an each method?

I created two scaffolds: announce_sections and announcements. The announce_sections are the types of announcements there are (i.e. games, tryouts, etc) and when I create an announcement I specify what type of announce_sections it is. I'm trying to display it so that each announce_section is viewed, with each announcement and its information under the announce_section. This is what I came up with:
<% #announce_sections.each do |announce_section| %>
<%= announce_section.name %>
<% #announcements.each do |announcement| %>
<%= announcement.announcement_title %>
<%= announcement.information %>
<%= announcement.additional_information %>
<%= announcement.type %>
<% end %>
<% end %>
However, this code only displays the announce_sections with the all announcements under it. The announcements don't get separated into their respective announce_sections. How do I change it so that it does?
<% #announce_sections.each do |announce_section| %>
<%= announce_section.name %>
<% #announcements.where(type: announce_section).each do |announcement| %>
<%= announcement.announcement_title %>
<%= announcement.information %>
<%= announcement.additional_information %>
<%= announcement.type %>
<% end %>
<% end %>
Use the name of the field you are using to assign the announcement type instead of 'type'
There are many ways to solve this, but one simple one is to build a hash where the key is the type of announcement_section and the value is an array (or Set) of the announcement. One way to build that hash is to use the Hash.new {|hash, key| ... } form of the constructor.
#hash = Hash.new {|hash, section| hash[section] = Array.new }
#announcements.each do |a|
# for each announcment append it to the array under the hash
#hash[a.section] << a
end
And then, in the view
<% #hash.keys.each do |section| %>
<%= section %>
<% #hash[section].each do |announcement| %>
<%= announcement.announcement_title %>
<%= announcement.information %>
<%= announcement.additional_information %>
<%= announcement.type %>
<% end %>
<% end %>

Nested output with related models

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

Resources