无法通过

时间:2017-11-23 10:04:35

标签: ruby-on-rails activerecord migration

我有:

ActiveRecord::Schema.define do
  create_table :jobs, force: true

  create_table :enquirers, force: true

  create_table :jobs_enquirers, force: true do |t|
    t.integer  "job_id"
    t.integer  "enquirer_id"
  end
end

class Job < ActiveRecord::Base
  has_one :jobs_enquirer, dependent: :destroy
  has_one :enquirer, through: :jobs_enquirer
end

class JobsEnquirer < ActiveRecord::Base
  belongs_to :job
  belongs_to :enquirer
end

class Enquirer < ActiveRecord::Base
  has_many :jobs_enquirers
  has_many :jobs, through: :jobs_enquirers
end

enquirer = Enquirer.create!
job = Job.create!(enquirer: enquirer)
puts Job.where(enquirer: enquirer)

但是当我尝试让post查询失败时。

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column jobs.enquirer_id does not exist
LINE 1: SELECT "jobs".* FROM "jobs" WHERE "jobs"."enquirer_id" = 1

如何指定正确的列?

全部要点:https://gist.github.com/anonymous/1cf19055e4ed147fd2f092ac7c78c9db

编辑:

我最后显式添加了连接表,并使用范围获取它。

在我的模特中

# app/models/job.rb
scope :with_enquirer, ->(enquirer) { joins(:jobs_enquirer).where(jobs_enquirer: { job_id: job }) }

1 个答案:

答案 0 :(得分:0)

您在db结构中将关联设置为many to many,但希望在代码结构中将其用作one to many

因此,您应该将其重新设为一个Post有多个Comment,然后:

  1. 删除表comments_posts和模型CommentPost
  2. post_id
  3. 中设置外键Comment
  4. 2关联:a)。在has_many :comments b)中添加Postbelongs_to :post' in Comment`
  5. 或者将它们设为Post并且属于许多Comment,然后:

    1. Posthas_many :comments_postshas_many :comments, through: :comments_post
    2. Commenthas_many :comments_postshas_many :posts, through: :comments_posthas_and_belongs_to_many没有through选项。您应该最好使用has_many ... through:协会
    3. 您应该选择的方式取决于您的业务需求和应用逻辑