Ruby on Rails, Using sort on each do - ruby-on-rails

I'm trying to use sort on each do. I get the error
wrong number of arguments(1 for 0)
I understand that I cannot daisy chain them together. Does anyone know another methods of getting this done.
<% Category.sort(:id).limit(4).each do |type| %>
<%= type.name %>
<% end %>
The result I am aiming for is to have all categories listed from a to z.

Assuming the Category is an Active Record then
<% Category.order(:id).limit(4).each do |type| %> would do the trick.

Related

How to check if an array index exists using Ruby and/or Rails

Is there a Ruby (preferably) or Rails way to check if the second index of an array exists?
In my Rails (4.2.6) app I have the following code in my view that shows the first two thumbnails for an array of photos:
<% if array.photos.any? %>
<%= image_tag array.photos.first.image.url(:thumb) %>
<%= image_tag array.photos[1].image.url(:thumb) %>
<% end %>
However if there is no second item in the array, then there is an error
I've tried the following if statements to make the rendering of the second thumbnail conditional, but they don't work:
<% if array.photos.include?(1) %>
<% if array.photos.second? %>
<% if array.photos[1]? %>
<% if array.photos[1].any? %>
I figured that another way to get what I want would be to simply check the length of the array
Still I was wondering if Ruby (or Rails) had a method or way to check if a specific index in an array exists or not. Thanks in advance
EDIT: To clarify I just want to show the first two thumbnails in the array, if any
You can use an .each, but if you want to follow this approach.
Instead of this:
<%= image_tag array.photos[1].image.url(:thumb) %>
Maybe you can use this:
<%= if(!array.photos[1].nil?) image_tag array.photos[1].image.url(:thumb) %>
Or:
<%= image_tag array.photos[1].image.url(:thumb) unless array.photos[1].nil? %>
Here, why not
(0...array.photos.size).each do |photo|
......
end
array.photos.each do |photo|
......
end

Ruby on Rails: Getting Value From Relationship

I have a loop to getting values in my database, but when I'm trying to get a value from a relationship, I get an error:
undefined method `first_name' for nil:NilClass
This is the loop:
<%= #sample.each do |s| %>
<%= s.relation.first_name %>
<% end %>
when I tried
<%= s.relation.to_json %>
with .to_json, I get this:
{"first_name":"testingtwo","last_name":"fdsaf","updated_at":"2013-11-21T07:47:05Z","user_id":null}
Shouldn't s.relation.first_name work?
Thanks
it's possible that there is a relation in the loop that doesn't have a value, and is getting hung up there - try this:
<%= #sample.each do |s| %>
<%= s.relation.first_name if s.relation %>
<% end %>
this only outputs s.relation.first_name if it isn't nil. You could also try this:
<%= #sample.each do |s| %>
<%= s.relation.first_name || "No name given" %>
<% end %>
which puts the first name if it exists, or "No name given" if it doesn't
One important thing you may want to consider too is whether or not having nil values within your database for that particular relationship is valid to begin with.
The || solution proposed is definitely a good one and a great Ruby pattern, but it may be worth adding in an ActiveRecord validation to ensure your relation(ships) are never nil.
ActiveRecord Validations are definitely the way to go in that particular case.

Stuck trying to list associated model

I think I am deeply misunderstanding how to write instances.
Miniatures have_many Manufacturers through the Productions table.
On the miniatures show page I am trying to list all the manufacturers for the current miniature and have them link the Manufacturer show page. Like so:
<% #miniature.manufacturers.each do |manufacturer| %>
<%= link_to #miniature.manufacturer.name, manufacturer_path %>
<% end %>
Needless to say it does not work. It gives "undefined method `manufacturer'".
I have tried A LOT of different combinations to no avail. The following version puts all the manufacturers, rolled into one link, once for each manufacturer a miniature has, and links to /manufacturers. A big mess.
<% #miniature.manufacturers.each do |manufacturer| %>
<%= link_to #miniature.manufacturers.map(&:name).join(', '), manufacturer_path %>
<% end %>
I have been working on other things and hoping I would get the hang of this but I'm pretty sure it's something pretty fundamental about how I set up the instance.
If it's more likely something I need to add to the controller then I can add my controller code here. Any help much appreciated.
Does this work:
<% #miniature.manufacturers.each do |manufacturer| %>
<%= link_to manufacturer.name, manufacturer_path(manufacturer) %>
<% end %>

Syntax for form_for when building an array from checkboxes

I'm making a form for an Order object, and the order has many Products, via a join table called OrderProducts. So, we've got something like this:
<% #order = Order.new %>
<% form_for #order do |f| %>
<% #products.each do |product| %>
... want to iterate over products here to build up "order[product_ids][]", with one checkbox per product
<% end %>
<% end %>
Usually for each product i would have a check_box_tag, saying
<%= check_box_tag "order[product_ids][]", product.id, #order.product_ids.include?(product.id) %>
But this, while working fine, always feels like a bit of a cop out. Is there a way i can do it with the f.check_box syntax? Important note - on the project in question I'm working in Rails 2.2.2, so a solution that works in rails 2 would be ideal.
Rails <= 2.x (original)
<% #products.each do |product| -%>
<% fields_for 'product[]' , product do |product_fields| -%>
[...]
<%= product_fields.check_box :id %>
<% end -%>
<% end -%>
Rails >= 3.x (updated)
<% #products.each do |product| -%>
<%= fields_for 'product[]' , product do |product_fields| -%>
[...]
<%= product_fields.check_box :id %>
<% end -%>
<% end -%>
I know the author was looking for version 2 answers, but this is the top hit for google and I though I would update:
One can do this ( I'm using 4.0, don't know how far back it goes ):
<%= form_for #order do |form| %>
<%= form.collection_check_boxes(:product_ids, Product.all, :id, :labeling_method ) %>
<% end %>
For more info: http://edgeapi.rubyonrails.org...
I've done a number of multi checkbox forms over the years and different Rails version. Rails has never provided any really clean way to do it, but the "cop out" solution you came up with is pretty good isn't it? It's one line, it's explicit, and as long as the list of products is reasonably short it will perform adequately.
To answer your specific question, f.check_box will never work for this. It's just short hand for the check_box_tag, but none of the semantics apply. If you want to go Rails native, the only possibility I think is to use nested attributes. Part of the problem is that there is not one obvious way for this type of thing to work. Rails core went through a lot of planning and feedback to come up with nested attributes as they exist, and though they seem a bit obtuse, they capture the most common use cases quite elegantly. But nested attributes were introduced in Rails 2.3, and besides they will introduce quite a bit of conceptual overhead for something which sounds like it doesn't need the complexity.
There are also some plugins that provide helpers for this, although I haven't used any in a long time (since Rails 2 era actually). My impression is that they too are overkill unless you have many forms that make use of this pattern.
In short, I think you should go ahead with your existing solution.
formastic gem
check_boxes option is very good to implement multiple checkboxes
like
f.input :yourcolumn, :as => :check_boxes, :collection => your_collection

Question with .find and a return value

I'm fairly new to rails (only about a month's experience), so this may be trivial. In my app, if I call
<%= Group.find(:all).each do |g| %>
<p><%= g.name %></p>
<%= end %>
it prints out all of the groups' names correctly. However, afterwards, it returns all of them (with the hexcodes, and stuff). I figure that's because .find returns everything you have it iterate over. Anyways - on to my question: Is .find the wrong method, or how do I go about iterating over every Group, without returning them afterwards?
I would appreciate any help or insight you all have.
Thanks!
I'm guessing you're doing something like
<%= Group.find(:all).each do |g| %>
<p><%= g.name %></p>
<%= end %>
That would print the return value of the whole statement. Instead, do this
<% Group.find(:all).each do |g| %>
<p><%= g.name %></p>
<% end %>
That wouldn't print the returned value.
Sidenote: Group.find(:all) is the same as Group.all

Resources