【问题标题】:ActiveRecord association not being set in the database?数据库中没有设置 ActiveRecord 关联?
【发布时间】:2015-10-14 17:49:16
【问题描述】:

我确定这是一个“duh”新手类型的问题,但我已经研究了好几天了,无法弄清楚为什么我的代码没有正确设置数据库中的关系。我有一个简单的 belongs_to两个模型之间的关系。

class Pod < ActiveRecord::Base
  belongs_to :instigator, :class_name => “User"

  attr_accessor :instigator, :instigator_id, :title

  validates_presence_of :instigator, :title
  validates_associated :instigator
end

class User < ActiveRecord::Base
  has_many :instigated_pods, inverse_of: :instigator, :class_name => "Pod", as: "instigator"
end

然后我想用 rspec 和 Factory Girl 来测试它们(我认为)又是非常简单的工厂

FactoryGirl.define do

  factory :pod do
    title           "Test pod"
    instigator
  end

  factory :user, aliases: [:instigator] do
    username
  end

end

使用此设置,大多数测试都通过了,但我的 PodsController 更新测试一直失败,我终于找到了一个说明原因的测试。

require 'rails_helper'

RSpec.describe Pod, type: :model do
  it "saves the relationship to the database" do
    pod = FactoryGirl.create(:pod)
    expect(pod.save).to be_truthy
    expect(pod.reload.instigator).to_not be_nil          # passes - cached?

    pod_from_database = Pod.find(pod.id)
    expect(pod_from_database.instigator).to_not be_nil   # <- fails
  end
end

似乎有什么东西阻止了在数据库中设置 pod.instigator_id,所以关系没有持久化。我也不知道为什么!!!

我尝试设置 validates_presence_of :instigator_id,但这使得大多数标准 rspec 测试失败,我从 the Rails Guides 看到了这一点:

如果您想确定是否存在关联,则需要进行测试 关联对象本身是否存在,而不是使用的外键 映射关联。

class LineItem < ActiveRecord::Base
  belongs_to :order
  validates :order, presence: true
end

为了验证需要存在的关联记录,您必须 为关联指定 :inverse_of 选项:

class Order < ActiveRecord::Base
  has_many :line_items, inverse_of: :order
end

如有任何帮助,我们将不胜感激!

【问题讨论】:

    标签: ruby-on-rails activerecord rspec associations factory-bot


    【解决方案1】:

    虽然我不太清楚为什么,但似乎删除了这条线

    attr_accessor :instigator, :instigator_id, :title
    

    解决问题。它似乎阻止写入这些属性。任何指标为什么会受到赞赏!

    【讨论】:

      【解决方案2】:

      attr_accessor 是一种 ruby​​ 方法,它可以生成 getter 和 setter(使它们能够被读取和写入),这不是 Rails 3 中称为 attr_accessible 的数据库字段。

      你所做的是声明一个 ruby​​ 方法,这就是它不起作用的原因。

      在这里阅读更多:

      http://rubyinrails.com/2014/03/17/what-is-attr_accessor-in-rails/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多