问题描述
我有3个模型. Rom::Favorite
,Rom::Card
,User
.我在创建User has_many rom_cards through rom_favorites
I have 3 models. Rom::Favorite
, Rom::Card
, User
. I am having an issue creating the 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
关联附带的所有实用程序方法都可以使用
All of the utility methods that come along with associations work except
a = User.find(1)
a.rom_cards
调用a.rom_cards
返回一个空数组,并且似乎正在运行此SQL查询
The call a.rom_cards
returns an empty array and it seems to run this SQL query
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方面不强,但我认为这似乎是正确的.
I am not strong in SQL, but I think this seems correct.
我知道a.rom_cards
应该返回2张卡片,因为a.rom_favorites
返回2个收藏夹,并且这些收藏夹中存在card_id.
I know a.rom_cards
should return 2 cards because a.rom_favorites
returns 2 favorites, and in those favorites are card_id's that exist.
应允许rom_cards
的呼叫如下
has_many :rom_cards, class_name: "Rom::Card", through: :rom_favorites, class_name: "Rom::Favorite"
我觉得这个问题与以下事实有关:它试图通过收藏夹查找用户"卡片,并且正在寻找card_id(因为我指定了Rom :: Card类)而不是rom_card_id.但是我可能是错的,不是很确定.
I feel like the issue has something to do with the fact that it is trying to find the Users cards through favorites and it is looking for card_id (because I specified the class Rom::Card) instead of rom_card_id. But I could be wrong, not exactly sure.
推荐答案
您正在复制关联哈希中的键class_name
.无需编写class_name: "Rom::Favorite"
,因为使用through: :rom_favorites
它将使用has_many :rom_favorites
的配置选项.
You are duplicating the key class_name
in the association hash. There is no need to write class_name: "Rom::Favorite"
because by using through: :rom_favorites
it will use the configuration options of has_many :rom_favorites
.
尝试:
has_many :rom_cards, class_name: "Rom::Card", through: :rom_favorites
这篇关于Rails:has_many通过不正确返回带有命名空间的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!