ruby on rails - How to Nest Models within a Model -
ruby on rails - How to Nest Models within a Model -
imagine have 2 models
film -name -description -duration -year_made -rating -actors actor -name -d_o_b -biography -films
actors nested in cinema , vice versa.
how represent relationship in ruby models? realistically have 3rd table mapping actor_id
film_id
.
whilst adding details cinema able create actor on fly(if actor not exist create new 1 name supplied)
thank in advance.
addition:
just found link similar question.
you're looking @ has , belongs many (habtm) relationship between 2 tables. read habtm relationship in rails guides here: http://edgeguides.rubyonrails.org/association_basics.html#has_and_belongs_to_many-association-reference
first you'll need generate migration this:
class addactorfilmtable < activerecord::migration def self.up create_table :actors_films, :id => false |t| t.integer :actor_id, :null => :false t.integer :film_id, :null => :false end add_index :actors_films, [:actor_id, :film_id], :unique => true end def self.down drop_table :actors_films end end
and specify in models:
class actor < activerecord::base has_and_belongs_to_many :films end class cinema < activerecord::base has_and_belongs_to_many :actors end
this allow utilize of additional rails methods type of relationship. utilize in form, follow railscast 17: habtm checkboxes - though it's old, should still apply. alternatively, can utilize gem simple form generate associations so:
form_for @actor |f| f.collection_check_boxes :film_ids, film.all, :id, :name end
ruby-on-rails model one-to-many
Comments
Post a Comment