I am using Ruby on Rails 3.0.7 and I am trying to save an "has_many :through => checkboxes
" class object (I have read the Quick Tip: has_many :through => checkboxes blog post) but I have some troubles on doing that. I would like to create some associations between a new article and article categories "owned" by a user (in the below code the @current_user
) taking advantage of the "magical way" of doing that with Ruby on Rails association models.
In my models I have:
class Article < ActiveRecord::Base
has_many :category_relationships,
:class_name => 'Categories::ArticleRelationship',
:foreign_key => 'article_id',
:autosave => true,
:dependent => :destroy
has_many :article_categories,
:through => :category_relationships,
:source => :article_category,
:uniq => true,
:dependent => :destroy
attr_accessible :category_relationship_ids
end
class Categories::ArticleRelationship < ActiveRecord::Base
belongs_to :article,
:class_name => 'Article',
:foreign_key => 'article_id'
belongs_to :article_category,
:class_name => 'Articles::Category',
:foreign_key => 'category_id'
end
In my view file I have:
...
<% @current_user.article_categories.each do |article_category| %>
<div>
<%= check_box_tag :category_relationship_ids, article_category.id, false, :name => 'article[category_relationship_ids][]' %>
<%= label_tag :article_category, article_category.name %>
</div>
<% end %>
...
that outputs the following HTML code:
<div>
<input type="checkbox" value="5" name="article[category_relationship_ids][]" id="category_relationship_ids">
<label for="category">comunication</label>
</div>
<div>
<input type="checkbox" value="6" name="article[category_relationship_ids][]" id="category_relationship_ids">
<label for="category">internal</label>
</div>
When I check\select the above two check boxes, (then) I submit the form and I inspect the log file (outputting @article
and @article_relationships
data respectively related to Article
and Categories::ArticleRelationship
object instances), I get the following:
param[:article] => {"name"=>"Sample title", "category_relationship_ids"=>["5", "6"], ...}
@article => #<Article id: nil, title: "Sample title", ...>
@article_relationships => [#<Categories::ArticleRelationship id: 5, category_id: 6, article_id: 3, ...>, [#<Categories::ArticleRelationship id: 6, category_id: 4开发者_开发问答, article_id: 5, ...>
It seems that Ruby on Rails set Categories::ArticleRelationship id
values to check box values (in the above HTML code: 5 and 6) instead of set those to nil
(those should be nil
because Categories::ArticleRelationship
are not created yet in the database). Furthermore, I don't know where it takes from the category_id
and article_id
values (article_id
values should be nil
because @article
instances are not created yet in the database).
What is the problem? How can I solve that?
精彩评论