Rails 5.2,Postgres 10.4
新手。我有一个has_many:through关系,我正在尝试加入,但是,尽管有我的定义,Rails似乎使用了错误的外键。
用户将通过机会注册来注册许多机会。一个机会可能会吸引许多用户。
opportunity.rb
class Opportunity < ApplicationRecord
has_many :opportunity_enrolment, :class_name => 'OpportunityEnrolment', :foreign_key => "opportunity_id"
has_many :volunteers, through: :opportunity_enrolment, :foreign_key => "opportunity_id"
end
opportunity_enrolment.rb
class OpportunityEnrolment < ApplicationRecord
has_many :opportunities, foreign_key: "id"
has_many :volunteers, foreign_key: "id"
end
users.rb
class Volunteer < ApplicationRecord
has_many :opportunity_enrolment, :class_name => 'OpportunityEnrolment', foreign_key: "volunteer_id"
has_many :opportunities, through: :opportunity_enrolment, foreign_key: "opportunity_id"
end
在显示特定用户然后将该用户加入其机会时,由于连接创建不正确,我在机会表中获得了第一条记录。
<% @volunteer.opportunities.each do |volunteerenrolment| %>
<table frame="box">
<tr><td>Name: <%= volunteerenrolment.oppname %></td></tr> --Oppname is in the opportunities table.
<tr><td>Created: <%= volunteerenrolment.created_at %></td></tr>
</table>
<% end %>
Rails创建以下select语句。
SELECT "opportunities".* FROM "opportunities" INNER JOIN "opportunity_enrolments" ON "opportunities"."id" = "opportunity_enrolments"."id" WHERE "opportunity_enrolments"."volunteer_id" = $1
opportunity_enrolments.id是机会表中的主键。我需要我的应用代替加入aboveal_enrolments.opportunity_id,就像这样:
SELECT "opportunities".* FROM "opportunities" INNER JOIN "opportunity_enrolments" ON "opportunities"."id" = "opportunity_enrolments"."opportunity_id" WHERE "opportunity_enrolments"."volunteer_id" = $1
在我的生命中,我不知道Rails从哪里提取了错误的外键。我试图在模型中多次更改它,但是Rails似乎不在那儿。如果我使用.joins手动编写正确的select语句,那么一切正常,但是我希望与“约定优先于配置”保持一致
谢谢!
答案 0 :(得分:0)
您的OpportunityEnrollment
表是您的Opportunity
和Volunteer
类之间的粘合剂,实际上应该使用belongs_to
。另外,您可以使用rails默认值来为您解释类名和外键。
也不要在名为“ users.rb”的文件中定义名为“ Volunteer”的类
opportunity.rb
class Opportunity < ApplicationRecord
# note the plural below as per rails convention
has_many :opportunity_enrolments
has_many :volunteers, through: :opportunity_enrolments
end
opportunity_enrolment.rb
class OpportunityEnrolment < ApplicationRecord
belongs_to :opportunity
belongs_to :volunteer
end
volunteer.rb
class Volunteer < ApplicationRecord
has_many :opportunity_enrolments
has_many :opportunities, through: :opportunity_enrolments
end
您的联接表应具有opportunity_id
和volunteer_id
字段。