gpt4 book ai didi

ruby-on-rails - Rails 3,具有 lambda 条件的 has_one/has_many

转载 作者:数据小太阳 更新时间:2023-10-29 08:28:08 26 4
gpt4 key购买 nike

这是我的模型:

class User < ActiveRecord::Base
has_many :bookmarks
end

class Topic < ActiveRecord::Base
has_many :bookmarks
end

class Bookmark < ActiveRecord::Base
belongs_to :user
belongs_to :topic
attr_accessible :position
validates_uniqueness_of :user_id, :scope => :topic_id
end

我想获取所有主题,对于current_user,相关的书签。 ATM,我做:

Topic.all.each do |t|
bookmark = t.bookmarks.where(user_id: current_user.id).last
puts bookmark.position if bookmark
puts t.name
end

这很丑陋并且做了太多的数据库查询。我想要这样的东西:

class Topic < ActiveRecord::Base
has_one :bookmark, :conditions => lambda {|u| "bookmarks.user_id = #{u.id}"}
end

Topic.includes(:bookmark, current_user).all.each do |t| # this must also includes topics without bookmark
puts t.bookmark.position if t.bookmark
puts t.name
end

这可能吗?我有其他选择吗?

谢谢!

最佳答案

*嗯,我不确定我是否理解您的问题,但这可能对您有所帮助:

# code
class Topic < ActiveRecord::Base
scope :for_user, lambda { |user| includes(:bookmarks).where(bookmarks: { user_id: user.try(:id) || user} ) }

# call
Topic.for_user(current_user) # => Array of Topics

如您所见,for_user 范围的参数 可以是用户对象或用户 ID

希望这对您有所帮助!

类似问题:

关于ruby-on-rails - Rails 3,具有 lambda 条件的 has_one/has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13515225/

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