Thursday 15 March 2012

Rails 4 - has_many through, splitting into 2 types using conditions -



Rails 4 - has_many through, splitting into 2 types using conditions -

i have working has_many through relationship between 2 models joining model.

company, film, companyfilm

many films have many companies. nice , easy, want define "type" of relationship on joining model, using conditions.

companyfilm has additional field called "role" can either "financier" or "publisher".

this current setup: (class film)

has_many :financier_companies, -> { where(company_films: {role: 'financier'}) }, :class_name => "companyfilm" has_many :financiers, :through => :financier_companies, :source => :company has_many :publisher_companies, -> { where(company_films: {role: 'publisher'}) }, :class_name => "companyfilm" has_many :publishers, :through => :publisher_companies, :source => :company

and form:

<%= f.label :financier_company_ids, "developers" %><br /> <%= f.select :financier_company_ids, company.all.collect {|financier| [financier.name, financier.id]}, {}, :multiple => true %>

on saving, error:

couldn't find companyfilm 'id'=2

any ideas? best practice have 1 field string define relationship, or improve have multiple boolean fields "financier?" , "publisher?". in example, possible company both. many thanks!

ruby-on-rails ruby-on-rails-4 has-many-through has-many rails-models

No comments:

Post a Comment