I am using Ruby on Rails 3.0.7 and I would like to save associated model class instances (I use an has_many :through => ...
association) on the creation time of the parent model. That is, I have the Article
, Category
and ArticleCategoryRelationship
classes: when I create a new article I would like to make it possible to use check boxes in order to choose related categories (these categories already exist in database) and on the creation\saving time to create a new article-category relationship for each checked\selected check box.
The problem seams to be related to the fact that when I save the article object it is not created yet and so I can not "automatically" add arti开发者_StackOverflow中文版cle-category relationships. That is, since in the ArticleCategoryRelationship
has article_is
and category_id
attributes, the article_id
attribute is not "automatically" populated with the article.id
value.
How can I handle the above situation in order to create article-category relationships (maybe taking advantage from the Ruby on Rails association model system)?
You have to use accepts_nested_attributes_for. Take a look at this railscast.
精彩评论