2017-03-09 116 views
0

我无法使用工厂女孩创建有效的评论工厂。我的评论模型属于可评论的并且是多态的。我已经尝试了一大堆不同的东西,但在那一刻,我的大多数测试中得到这个错误:FactoryGirl多态关联

ActiveRecord::RecordInvalid: 
    Validation failed: User can't be blank, Outlet can't be blank 

我不知道为什么它不经过验证,尤其是因为我的评论模型验证USER_ID和outlet_id,而不是用户和出口中存在

这里是我厂:

factory :comment do 
    body "This is a comment" 
    association :outlet_id, factory: :outlet 
    association :user_id, factory: :user 
    #outlet_id factory: :outlet 
    association :commentable, factory: :outlet 
end 

class CommentsController < ApplicationController 

def new 
    @comment = Comment.new 
end 

def create 
    @outlet = Outlet.find(params[:outlet_id]) 
    @comment = @outlet.comments.build(comment_params) 
    @comment.user_id = User.find(params[:user_id]).id 


    if @comment.save 
     redirect_to(@outlet) 
    end 
end 

def edit 
    @comment = Comment.find(params[:id]) 
end 

def update 
    @comment = Comment.find(params[:id]) 

    if @comment.update(comment_params) 
     redirect_to @comment.outlet 
    end 
end 

def destroy 
    @comment = Comment.find(params[:id]) 

    if @comment.destroy 
     redirect_to @comment.outlet 
    end 
end 


private 
def comment_params 
    params.require(:comment).permit(:body, :outlet_id, :user_id) 
end 

结束


class Comment < ApplicationRecord 
    belongs_to :commentable, polymorphic: true 

    validates :body, :user_id, :outlet_id, presence: true 
    validates :body, length: { in: 1..1000 } 
end 

+0

如果删除了验证会发生什么'验证:USER_ID,:outlet_id,存在:TRUE'? – Fredius

+0

测试会通过,但我觉得我应该验证每个评论都有它所属的user_id和outlet_id,不是吗? –

+0

烨,但我不明白你为什么不使用模型,而不是IDS – Fredius

回答

0

是否有使用association :user_id一个特别的原因?

你可能想要更多的东西一样:

factory :comment do 
    body "This is a comment" 
    association :outlet, factory: :outlet 
    association :user, factory: :user 
    association :commentable, factory: :outlet 
end 

顺带可以简化为:

factory :comment do 
    body "This is a comment" 
    outlet 
    user 
    association :commentable, factory: :outlet 
end 
+0

是的,我之所以使用user_id是因为我得到一个没有方法的错误,说该评论没有“用户”方法 –

+0

@HarryB。你可以添加'belongs_to:user'和'belongs_to:outlet'到'Comment'?我试图理解为什么你直接在这里引用'_id'字段。 – gwcodes