Ruby on rails 数据库中未设置ActiveRecord关联?

Ruby on rails 数据库中未设置ActiveRecord关联?,ruby-on-rails,activerecord,rspec,associations,factory-bot,Ruby On Rails,Activerecord,Rspec,Associations,Factory Bot,我肯定这是一个“duh”新手类型的问题,但我已经问了好几天了,不明白为什么我的代码没有在数据库中正确设置关系。我有一个简单的两个模型之间的归属关系 class Pod < ActiveRecord::Base belongs_to :instigator, :class_name => “User" attr_accessor :instigator, :instigator_id, :title validates_presence_of :instigator,

我肯定这是一个“duh”新手类型的问题,但我已经问了好几天了,不明白为什么我的代码没有在数据库中正确设置关系。我有一个简单的两个模型之间的归属关系

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
有了这个设置,大多数测试都通过了,但我的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
为了验证需要存在的关联记录,您必须 指定关联的
:反向\u
选项:

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

如果您能帮我解决这个问题,我将不胜感激!

虽然我不完全清楚原因,但似乎要删除该线路

attr_accessor :instigator, :instigator_id, :title

解决了这个问题。它似乎阻止了写入这些属性。任何指示器都值得赞赏!

attr\u accessor
是一种ruby方法,用于生成getter和setter(使它们能够读取和写入),而不是Rails 3中称为
attr\u accessible
的数据库字段

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

请在此处阅读更多信息:

class LineItem < ActiveRecord::Base
  belongs_to :order
  validates :order, presence: true
end
class Order < ActiveRecord::Base
  has_many :line_items, inverse_of: :order
end
attr_accessor :instigator, :instigator_id, :title