我的many-to-many
帖子和类别模型之间存在关联。我将类别字段添加为帖子的嵌套属性:
post_controller.rb:
def new
@post = Post.new
end
帖子/new.html.erb:
<%= f.select :category_ids, Category.all.collect {|c| [c.name, c.id]} %>
分类.rb:
class Categorization < ActiveRecord::Base
attr_accessible :category_id, :post_id, :position
belongs_to :post
belongs_to :category
end
类别.rb:
class Category < ActiveRecord::Base
attr_accessible :name
has_many :categorizations
has_many :posts, :through => :categorizations
validates :name, presence: true, length: { maximum: 14 }
end
post.rb:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :category_ids
has_many :categorizations
has_many :categories, :through => :categorizations
end
<%= f.select :category_ids, Category.all.collect {|c| [c.name, c.id]} %>
现在,提交表单后,我得到如下信息:
[#<Category id: 2, name: "Design", created_at: "2012-11-23 10:12:54", updated_at: "2012-11-23 10:12:54">, #<Category id: nil, name: nil, created_at: nil, updated_at: nil>]
我不知道额外的 nil 类别来自哪里。
可能是什么原因?
编辑:
发布新的:
提交后生成的html: