bekite
bekite

Reputation: 3444

Rails 3 Nested Attributes and Access Association Attribute

I have the following scenario: A product can be sold by different providers for a given price. In my form for the product, I want to select the providers through checkboxes and assign a price for the selected providers.

My model:

product.rb

class Product < ActiveRecord::Base
  belongs_to :price
  has_many :providers, through: :price

  accepts_nested_attributes_for :providers, :price
end

# == Schema Information
#
# Table name: products
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  isbn       :integer
#  created_at :datetime        not null
#  updated_at :datetime        not null

provider.rb

class Provider < ActiveRecord::Base
  belongs_to :price
  has_many :products, through: :price
end

# == Schema Information
#
# Table name: providers
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  created_at :datetime        not null
#  updated_at :datetime        not null

price.rb

class Price < ActiveRecord::Base
  belongs_to :product
  belongs_to :provider
end

# == Schema Information
#
# Table name: prices
#
#  id          :integer         not null, primary key
#  value       :decimal(, )
#  created_at  :datetime        not null
#      updated_at  :datetime        not null
#  product_id  :integer
#  provider_id :integer

app/views/products/_form.html.erb

<%= form_for(@product) do |f| %>
...
<div class="field">
    <% Provider.all.each do |provider| %>
      <%= check_box_tag "product[provider_ids][]", provider.id, @product.provider_ids.include?(provider.id), id: dom_id(provider) %>
          <%= label_tag dom_id(provider), provider.name %>
    <% end %>

    <% f.fields_for :price do |price_form| %>
      <%= price_form.text_field :value %>
    <% end %>
    <br>
</div>
...

I didn't change anything in the products_controller. I tried to access the association attribute price.value through the following code in my form.

<%= f.fields_for :price do |price_form| %>
    <%= price_form.text_field :value %>
<% end %>

But no text_field are displayed near the checkboxes and when I select one provider and submit the form, I get the following error:

can't write unknown attribute `price_id'

Upvotes: 2

Views: 988

Answers (2)

prijutme4ty
prijutme4ty

Reputation: 139

Change belongs_to :price in Product class into has_one :price. You should use belongs_to :attribute method on models which has attribute_id in its table.

Upvotes: 1

ghost79
ghost79

Reputation: 151

You need to change

<% f.fields_for :price do |price_form| %>
    <%= price_form.text_field :value %>
<% end %>

to

<%= f.fields_for :price do |price_form| %>
    <%= price_form.text_field :value %>
<% end %>

Upvotes: 0

Related Questions