Reputation: 13
I'm pretty new to rails but started having this issue today which i haven't experienced before. Currently working on an application with a few nested associations. While i can create and add save these nested associations through the parent association i can't seem to call on elements from the associated model very well. I can see the information has been saved but when I call for it i get the name of the model not what is in the name column of the table.
brew.rb
class Brew < ActiveRecord::Base
has_many :fermentables
has_many :extras
has_many :hops
has_many :yeasts
accepts_nested_attributes_for :hops
end
hop.rb
class Hop < ActiveRecord::Base
belongs_to :brew
end
show.html.erb
<%= @brew.name %>
<%= @brew.story %>
<%= @brew.walkthrough %>
<%= @brew.hops.name%>
The show displays mostly everything just fine except when it comes to @brew.hops.name. It only displays Hop. When I go into rails console I can see that the name had been saved. But only when I do something like.
t = Brew.last
t.hops.name
results only in the word "hops"
but if i just say
t.hops
i get
` SELECT "hops".* FROM "hops" WHERE "hops"."brew_id" = ? [["brew_id", 28]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Hop id: 6, name: "Warrior",
brew_id: 28, created_at: "2013-06-09 22:09:19", updated_at: "2013-06-09 22:09:19">]> `
Upvotes: 1
Views: 328
Reputation: 51151
Brew and hops are in relation one-to-many, so @brew.hops
returns set of all hops belonging to @brew
. So, if you want to display all associated hops
names, you should do something like this:
<% @brew.hops.each do |hop| %>
<%= hop.name %><br />
<% end %>
Upvotes: 1
Reputation: 11588
t.hops
returns an object representing the has_many
association itself, not an individual Hop record, and calling the name
method on that association object gives the name of the class of the associated model (the Hop class).
So I think you are wanting to iterate over the list of associated Hops and print each of their names:
<%- @brew.hops.each do |hop| -%>
Hop: <%= hop.name %>
<%- end -%>
Upvotes: 0