繁体   English   中英

Rails:has_many通过没有正确返回命名空间模型

[英]Rails: has_many through not returning correctly with namespaced models

我有3个型号。 Rom::FavoriteRom::CardUser 我在User has_many rom_cards through rom_favorites创建User has_many rom_cards through rom_favorites时遇到问题

这是我模型的相关部分

罗::卡

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

罗::收藏

   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。 但我可能是错的,不完全确定。

您正在复制关联哈希中的密钥class_name 没有必要编写class_name: "Rom::Favorite"因为通过使用class_name: "Rom::Favorite" through: :rom_favorites它将使用has_many :rom_favorites的配置选项。

试试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM