I have a basic question of relationship in RoR :
In a view, I try to display the t开发者_C百科itle of a group, which is in the table "groups", and only the key "group_id" is stored in the table/object "product".
When I write product.group_id, I see the value in the database, but if I write product.group.title, RoR tolds me undefined method `group' for #.
This is a basic question so I appreciate your help !
The code in the view (this works but is so awful ! I'm sure there is a way like product.group.title)
<% @products.each do |product| %>
<%= Group.find(product.group_id).title %> </td>
<% end %>
and the models :
class Group < ActiveRecord::Base
has_many :products, :dependent => :destroy
end
class Product < ActiveRecord::Base
belongs_to :groups
has_and_belongs_to_many :authors
end
Should be belongs_to :group
not groups
Also, in your view, you could more easily do this:
<% @products.each do |product| %>
<%= product.group.title %> </td>
<% end %>
精彩评论