samedi 25 juillet 2015

How to organize form_for helper to show data from different models?

I have three models PriceGroup, PriceGroupLine and Item. PriceGroup has fields - :id and :name. Item has fields - :id and :name. PriceGroupLine has fields - :id, :price_group_id, :item_id, :price

Associations:

PriceGroup has_many PriceGroupLines

Item has_one PriceGroupLine

PriceGroupLine belongs_to Item

PriceGroupLine belongs_to PriceGroup

I need to insert in PriceGroupLine model lines from PriceGroup show view. How I should organize form_for helper if I need to insert in PriceGroupLine:

item_id - items list organized with collection_select helper
price_group_id
price of item

And one more question about the associations. At the beginning i had associations like:

PriceGroup has_many PriceGroupLines

PriceGroupLine has_many Items

Item belongs_to PriceGroupLine

PriceGroupLine belongs_to PriceGroup

But this associations didn't work correctly when i tried to get :name field from Item model like this:

<% @price_group.price_group_lines.each do |price_group_line| %>
  <%= price_group_line.item.try(:name) %>>
  <%= price_group_line.price %>
<% end %>

I changed associations and all worked. Now PriceGroupLine belongs_to :item and Item has_one :price_group_line. But it is logical to assume that ITEM is belongs to PriceGroupLine (PRICEGROUPLINE contains ITEM). Am I wrong?

Aucun commentaire:

Enregistrer un commentaire