2017-03-09 119 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