我有:
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 }) }
答案 0 :(得分:0)
您在db结构中将关联设置为many to many
,但希望在代码结构中将其用作one to many
。
因此,您应该将其重新设为一个Post
有多个Comment
,然后:
comments_posts
和模型CommentPost
post_id
Comment
has_many :comments
b)中添加Post
。 belongs_to :post' in
Comment` 或者将它们设为Post
并且属于许多Comment
,然后:
Post
:has_many :comments_posts
和has_many :comments, through: :comments_post
Comment
:has_many :comments_posts
和has_many :posts, through: :comments_post
(has_and_belongs_to_many
没有through
选项。您应该最好使用has_many ... through:
协会您应该选择的方式取决于您的业务需求和应用逻辑