Ruby on rails 在Rails中的has_many到中添加附加属性
我成立了以下协会:Ruby on rails 在Rails中的has_many到中添加附加属性,ruby-on-rails,associations,has-many-through,rails-models,Ruby On Rails,Associations,Has Many Through,Rails Models,我成立了以下协会: class BookLaunch < ApplicationRecord has_many :book_launch_locations, dependent: :destroy has_many :stores, through: :book_launch_locations .... class Store < ApplicationRecord has_many :book_launch_locations has_many :
class BookLaunch < ApplicationRecord
has_many :book_launch_locations, dependent: :destroy
has_many :stores, through: :book_launch_locations
....
class Store < ApplicationRecord
has_many :book_launch_locations
has_many :book_launch, through: :book_launch_locations
....
class BookLaunchLocation < ApplicationRecord
belongs_to :book_launch, :touch => true
belongs_to :store
end
我想将book\u price
添加到BookLaunch模型中的商店中,以便在调用
@book\u launch.stores
,它将具有stores的所有属性+book\u price
属性
这可能吗
我用fastJsonApi这样称呼它:
options = {
include: [:book_launch, :'book_launch.properties']}
json = Api::launchSummarySerializer.new(summaryData, options).serialized_json
render json: json
如果要创建包含两个以上外键列的联接模型行,则需要显式地而不是隐式地创建它 隐式创建联接模型行是指通过间接关联创建联接模型行:
Store.first.book_launches.create!(attributes)
BookLaunch.first.stores.create!(attributes)
抱歉,我对rails真的很生疏。我只有一个控制器,可以找到一个特定的book_launch并返回book_launch.stores。我只想在返回book_launch.stores时包含book_price属性。你是说这将通过我创建它的方式来解决吗?你在处理问题时真的错了。您要做的是遍历
book\u launch\u locations
关联<代码>book|u launch.book|u launch|u locations.each{bll |放置“{bll.store.name}:{bll.price}”}。如果你能找到一个更好的名字,这段代码就不会那么尴尬了。我只是用我的名字更新了我的代码。是的,名字不好。因此,听起来我无法将门店与book_launch_位置的属性价格结合起来。我得分别打两个电话
store = Store.first
book_launch = BookLaunch.first
BookLaunchLocation.create(
store: store,
book_launch: book_launch,
price: 999
)
# or
store.book_launch_locations.create(
book_launch: book_launch,
price: 999
)
# or
book_launch.book_launch_locations.create(
store: store,
price: 999
)
Store.first.book_launches.create!(attributes)
BookLaunch.first.stores.create!(attributes)