gpt4 book ai didi

ruby-on-rails - Rails has_many :through and Setting Property on Join model

转载 作者:行者123 更新时间:2023-12-04 04:39:29 24 4
gpt4 key购买 nike

this question相似,如何在此上下文中保存之前在连接模型上设置属性?

class Post < ActiveRecord::Base
has_many :post_assets
has_many :assets, :through => :post_assets
has_many :featured_images, :through => :post_assets, :class_name => "Asset", :source => :asset, :conditions => ['post_assets.context = ?', "featured"]

end

class PostAssets < ActiveRecord::Base
belongs_to :post
belongs_to :asset

# context is so we know the scope or role
# the join plays
validates_presences_of :context
end

class Asset < ActiveRecord::Base
has_many :post_assets
has_many :posts, :through => :post_assets
end

我只是想能够做到这一点:
@post = Post.create!(:title => "A Post")
@post.featured_images << Asset.create!(:title => "An Asset")
# ...
@post = Post.first
@featured = @post.featured_images.first
#=> #<Asset id: 1, title: "An Asset">
@featured.current_post_asset #=> #<PostAsset id: 1, context: "featured">

那将如何工作?我整天都在努力奋斗:)。

当前发生的是当我这样做时:
@post.featured_images << Asset.create!(:title => "An Asset")

然后,创建的联接模型 PostAsset将永远没有机会设置 context。如何设置上下文属性?看起来像这样:
PostAsset.first #=> #<PostAsset id: 1, context: nil>

更新:

我创建了一个测试 gem以尝试找出问题所在。有没有更简单的方法可以做到这一点?

有了 ActsAsJoinable::Core class,您就可以在联接模型中通过它们之间的上下文建立多对多关系。并且它添加了辅助方法。基本的 tests基本上显示了我要执行的操作。关于如何正确执行此操作的更好的主意吗?

最佳答案

查看位于以下位置的ActiveRecord::Associations::ClassMethods API中的has_many选项:http://rails.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001316

这是最有趣的报价:

:conditions

Specify the conditions that the associated object must meet in order to be included as a WHERE SQL fragment, such as authorized = 1. Record creations from the association are scoped if a hash is used. has_many :posts, :conditions => {:published => true} will create published posts with @blog.posts.create or @blog.posts.build.



因此,我相信您的条件必须指定为哈希,如下所示:
class Post < ActiveRecord::Base
has_many :post_assets
has_many :featured_post_assets, :conditions => { :context => 'featured' }

has_many :assets, :through => :post_assets

has_many :featured_images, :through => :featured_post_assets,
:class_name => "Asset", :source => :asset,
end

并且您还应该执行以下操作:
@post.featured_images.build(:title => "An asset")

代替:
@post.featured_images << Asset.create!(:title => "An Asset")

如上引言所述,这应调用范围内的 Assets 构建,以将上下文字段添加到 Assets 。它还将在一个原子事务中同时将联接模型对象(post_asset)和 Assets 对象保存到数据库中。

关于ruby-on-rails - Rails has_many :through and Setting Property on Join model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3081764/

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