gpt4 book ai didi

ruby-on-rails - rails : has_many through not returning correctly with namespaced models

转载 作者:数据小太阳 更新时间:2023-10-29 07:02:54 25 4
gpt4 key购买 nike

我有 3 个模型。 Rom::FavoriteRom::CardUser。我在创建 User has_many rom_cards through rom_favorites

时遇到问题

这是我模型的相关部分

Rom::Card

class Rom::Card < ActiveRecord::Base
has_many :rom_favorites, class_name: "Rom::Favorite", foreign_key: "rom_card_id", dependent: :destroy

self.table_name = "rom_cards"

end

用户

class User < ActiveRecord::Base
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :role

has_many :rom_favorites, class_name: "Rom::Favorite", dependent: :destroy
has_many :rom_cards, class_name: "Rom::Card", through: :rom_favorites, class_name: "Rom::Favorite"

end

Rom::收藏

   class Rom::Favorite < ActiveRecord::Base
attr_accessible :rom_card_id, :user_id

belongs_to :user
belongs_to :rom_card, class_name: "Rom::Card"

validates :user, presence: true
validates :rom_card, presence: true
validates :rom_card_id, :uniqueness => {:scope => :user_id}

self.table_name = "rom_favorites"

end

除了

之外,关联的所有实用方法都有效
a = User.find(1)
a.rom_cards

调用 a.rom_cards 返回一个空数组,它似乎运行了这个 SQL 查询

SELECT "rom_favorites".* FROM "rom_favorites" INNER JOIN "rom_favorites" "rom_favorites_rom_cards_join" ON "rom_favorites"."id" = "rom_favorites_rom_cards_join"."rom_card_id" WHERE "rom_favorites_rom_cards_join"."user_id" = 1

我不擅长 SQL,但我认为这似乎是正确的。

我知道 a.rom_cards 应该返回 2 张卡片,因为 a.rom_favorites 返回 2 个收藏夹,并且在这些收藏夹中存在 card_id。

应该允许 rom_cards 的调用如下

has_many :rom_cards, class_name: "Rom::Card", through: :rom_favorites, class_name: "Rom::Favorite"

我觉得这个问题与以下事实有关:它试图通过收藏夹查找用户卡,并且它正在寻找 card_id(因为我指定了 Rom::Card 类)而不是 rom_card_id。但我可能是错的,不确定。

最佳答案

您正在复制 key class_name在关联哈希中。不用写class_name: "Rom::Favorite"因为通过使用 through: :rom_favorites它将使用 has_many :rom_favorites 的配置选项.

尝试:

has_many :rom_cards, class_name: "Rom::Card", through: :rom_favorites

关于ruby-on-rails - rails : has_many through not returning correctly with namespaced models,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18539202/

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