我宣布以下模型如下:
class Comment belongs_to :commentable,polymorphic: true belongs_to :userendclass Userendclass Storyend
现在,我想声明一个具有FactoryGirl的注释对象,该对象属于与值得称赞的用户和用户相同的用户.
到目前为止,这是我的代码:
FactoryGirl.define do factory :user do sequence(:email) {|n| "person#{n}@exmaple.com"} sequence(:slug) {|n| "person#{n}"} end factory :comment do occured_at { 5.hours.ago } user association :commentable,factory: :user endend
这里的问题是编写评论的用户和值得称道的用户不一样.
我为什么要解决这个问题?
很多TNX
解决方法 首先,我认为你没有完成你的协会……我认为这就是你想要的:class Comment < AR belongs_to :commentable,polymorphic: trueendclass User < AR has_many :comments,as: :commentableendclass Story < AR has_many :comments,as: :commentableend
见:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
不要忘记数据库设置.
其次,Factory Setup会返回两个用户,因为您正在告诉它.尝试:
FactoryGirl.define do factory :user do sequence(:email) {|n| "person#{n}@exmaple.com"} sequence(:slug) {|n| "person#{n}"} end factory :comment do occured_at { 5.hours.ago } association :commentable,factory: :user endend
作为一种风格问题,模型名称的选择在这里有点令人困惑.用户如何“可评论”?如果你的意思是其他类型的写作,我会选择一个不同的名字.同上,如果你的意思是“用户个人资料”或类似的东西.
总结以上是内存溢出为你收集整理的ruby-on-rails-3 – 如何定义与工厂女孩的多态关联全部内容,希望文章能够帮你解决ruby-on-rails-3 – 如何定义与工厂女孩的多态关联所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)