gpt4 book ai didi

ruby-on-rails - Ruby on Rails - 通过连接在 has_many 中使用了错误的外键

转载 作者:行者123 更新时间:2023-11-29 13:43:48 25 4
gpt4 key购买 nike

Rails 5.2,Postgres 10.4

rails 新手。我有一个 has_many :through 关系,我试图加入,但是,尽管我定义了,但 Rails 似乎使用了错误的外键。

用户将通过机会注册来注册许多机会。一个机会可能有很多用户注册。

机会.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

用户.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 "opportunities".* FROM "opportunities" INNER JOIN "opportunity_enrolments" ON "opportunities"."id" = "opportunity_enrolments"."id" WHERE "opportunity_enrolments"."volunteer_id" = $1

opportunity_enrolments.id 是 opportunity_enrolments 表的主键。我需要我的应用程序加入 opportunity_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 语句,那么一切都会完美无缺,但我想与“约定优于配置”保持一致

谢谢!

最佳答案

OpportunityEnrollment 表是OpportunityVolunteer 类之间的粘合剂,实际上应该使用belongs_to .另外,您可以使用 rails defaults,它会为您解释类名和外键。

也不要在名为“users.rb”的文件中定义一个名为“Volunteer”的类

机会.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

志愿者.rb

class Volunteer < ApplicationRecord
has_many :opportunity_enrolments
has_many :opportunities, through: :opportunity_enrolments
end

您的连接表应该有 opportunity_idvolunteer_id 字段。

关于ruby-on-rails - Ruby on Rails - 通过连接在 has_many 中使用了错误的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com