Rails 指定外键和 where 选项的关联
Rails association that specifies foreign key and where options
我正在尝试关联两个 table,其中特定条件为真。
这是一种'user has books in a collection' 模式。 collection 可以是 图书馆 或 愿望清单 。
有一个用户 table(相当标准)、一本书 table(细节无关)和一个名为 collection_books 的联接 table,它看起来像这样:
编号 | user_id | book_id | collection_type
使用Rails Docs作为参考,我的代码如下所示:
class User < ApplicationRecord
has_many :library_collection_books,
foreign_key: :user_id,
class_name: :CollectionBook,
-> { where collection_type: 'library'}
end
对比 Rails 文档示例代码:
class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies,
-> { where "factory = 'Seattle'" }
end
这是我在 rails 控制台中得到的错误:
user.rb:36: syntax error, unexpected '\n', expecting =>
我猜它不是特定于 has_and_belongs_to
关联类型,所以问题一定是我指定外键和 class 名称的语法。
郑重声明,我可以做到
has_many :collection_books,
-> { where collection_type: 'library' }
它确实有效。但我需要图书馆或愿望清单书籍的这种关联。
lambda -> { ... }
必须是第一个参数 (或者第二个取决于你如何计算它)
has_many :library_collection_books,
-> { where collection_type: 'library'},
foreign_key: :user_id,
class_name: 'CollectionBook'
我正在尝试关联两个 table,其中特定条件为真。
这是一种'user has books in a collection' 模式。 collection 可以是 图书馆 或 愿望清单 。
有一个用户 table(相当标准)、一本书 table(细节无关)和一个名为 collection_books 的联接 table,它看起来像这样:
编号 | user_id | book_id | collection_type
使用Rails Docs作为参考,我的代码如下所示:
class User < ApplicationRecord
has_many :library_collection_books,
foreign_key: :user_id,
class_name: :CollectionBook,
-> { where collection_type: 'library'}
end
对比 Rails 文档示例代码:
class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies,
-> { where "factory = 'Seattle'" }
end
这是我在 rails 控制台中得到的错误:
user.rb:36: syntax error, unexpected '\n', expecting =>
我猜它不是特定于 has_and_belongs_to
关联类型,所以问题一定是我指定外键和 class 名称的语法。
郑重声明,我可以做到
has_many :collection_books,
-> { where collection_type: 'library' }
它确实有效。但我需要图书馆或愿望清单书籍的这种关联。
lambda -> { ... }
必须是第一个参数 (或者第二个取决于你如何计算它)
has_many :library_collection_books,
-> { where collection_type: 'library'},
foreign_key: :user_id,
class_name: 'CollectionBook'