Mr_Nizzle
Mr_Nizzle

Reputation: 6714

has_many association with conditions on ActiveRecord

I have this models: Store and Address.

The second model Address I'm using this with other models and has some custom fields inside for different models.

Yes like polymorphic but without the varchar field for Class, I'm using an integer. (optimization stuff)

now on my Store model the association in set like this:

class Store < ActiveRecord::Base
    has_many :addresses, :foreign_key => "parent_id", :conditions => ['parent_kind = ?', 2]
    accepts_nested_attributes_for :addresses
end 

Now in my controller I do:

@store.addresses.build

And I can use f.fields_for :addresses... inside the form.

The problem comes out when I submit the form and the data is saved to the database.

The record in the stores table is saved, the record in addresses is saved with the parent_id of the store in place, but the parent_kind is in 0 which is the default value for that attribute on MySQL.

My Quick fix was this:

@store = Store.new(params[:store])
    @store.addresses[0].parent_kind = 2
    if @store.save
    ....

But I know there must be another way.

Anny suggestions?

Thanks.

Upvotes: 0

Views: 2210

Answers (1)

HargrimmTheBleak
HargrimmTheBleak

Reputation: 2167

Did you try using a hidden field in your nested form?

<%= f.fields_for :addresses, Address.new do |ff| %>
  <%= ff.hidden_field :parent_kind, :value => 2 %>
  ...

EDIT

If you don't want to use it due to security concerns, here's another way that might help. You can try using an association callback like so:

class Store < ActiveRecord::Base
  has_many :addresses, :foreign_key => "parent_id", 
                       :conditions => ['parent_kind = ?', 2],
                       :before_add => Proc.new { |store,address| address.parent_kind = 2}
  accepts_nested_attributes_for :addresses
end 

Upvotes: 2

Related Questions