【发布时间】:2012-11-12 08:29:23
【问题描述】:
我在Post 和Category 模型之间有一个many-to-many 关联:
categorization.rb:
class Categorization < ActiveRecord::Base
attr_accessible :category_id, :post_id, :position
belongs_to :post
belongs_to :category
end
category.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) }
我的问题就在这里:
factories.rb:
factory :post do
title "Lorem"
content "Lorem ipsum"
category_ids category
user
end
factory :category do
name "Lorem"
end
reply_spec.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>
我认为这是不起作用的部分:
factories.rb:
category_ids category
我是否以错误的方式定义了嵌套属性?什么是正确的?
【问题讨论】:
-
查看此链接factory girl,也许正是您需要的。
-
@Kien Thanh 谢谢,我认为它有一些有用的概念,但我认为它是针对
has_and_belongs_to_many关联的。不是我在这里使用的:many => through。