我在 a和模型many-to-many
之间有关联:Post
Category
分类.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
accepts_nested_attributes_for :categorizations, allow_destroy: true
end
这有效:
post_spec.rb:
describe Post do
let(:user) { FactoryGirl.create(:user) }
let(:category) { FactoryGirl.create(:category) }
before { @post = user.posts.build(title: "Lorem ipsum",
content: "Lorem ipsum dolor sit amet",
category_ids: category) }
我的问题在这里:
工厂.rb:
factory :post do
title "Lorem"
content "Lorem ipsum"
category_ids category
user
end
factory :category do
name "Lorem"
end
回复规格.rb:
describe Reply do
let(:post) { FactoryGirl.create(:post) }
let(:reply) { post.replies.build(content: "Lorem ipsum dolor sit amet") }
当我运行测试时,reply_spec.rb
我收到此错误:
> undefined method `category=' for #<Post:0x9e07564>
这是我认为不起作用的部分:
工厂.rb:
category_ids category
我是否以错误的方式定义嵌套属性?什么是合适的?