【问题标题】:FactoryGirl polymorphic associationsFactoryGirl 多态关联
【发布时间】:2017-03-09 18:25:10
【问题描述】:

我无法使用工厂女孩创建有效的评论工厂。我的评论模型属于可评论的,是多态的。我已经尝试了很多不同的东西,但目前,我的大多数测试都因这个错误而失败:

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

我不确定为什么它没有通过验证,尤其是因为我的评论模型验证了 user_id 和 outlet_id 的存在,而不是 User 和 Outlet

这是我的工厂:

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

【问题讨论】:

  • 如果您删除验证 validates :user_id, :outlet_id, presence: true 会发生什么?
  • 测试会通过,但我觉得我应该验证每个评论都有属于它的 user_id 和 outlet_id,不是吗?
  • 是的,但我不明白你为什么不使用模型而不是 ids
  • 当我将验证更改为用户和出口时,我得到的为什么我没有有效工厂的错误是:NoMethodError: undefined method `user' for #<0x007f9a7e45b058>

标签: ruby-on-rails ruby tdd factory-bot


【解决方案1】:

使用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

【讨论】:

  • 是的,我使用 user_id 的原因是因为我收到一个 no method 错误,说评论没有方法“user”
  • @HarryB。您可以将belongs_to :userbelongs_to :outlet 添加到Comment?我试图了解您为什么在此处直接引用 _id 字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多