Ruby on rails 困难的情况
在我的应用程序中,用户可以启动并参与讨论。他们还可以标记讨论;当他们这样做时,会创建一个包含标签名称的标签(如果标签不存在的话),并且还会创建一个标签,它会记住哪个用户使用哪个标签标记了哪个讨论 因此,在讨论模型中,我们有:Ruby on rails 困难的情况,ruby-on-rails,named-scope,Ruby On Rails,Named Scope,在我的应用程序中,用户可以启动并参与讨论。他们还可以标记讨论;当他们这样做时,会创建一个包含标签名称的标签(如果标签不存在的话),并且还会创建一个标签,它会记住哪个用户使用哪个标签标记了哪个讨论 因此,在讨论模型中,我们有: has_many :taggings has_many :tags, :through => :taggings 我正在尝试创建一种简单的方法,从一个用户检索讨论中的所有标记。理想情况下,命名的_范围将被明智地使用,以保持事物的整洁。我认为应该是这样的: tags
has_many :taggings
has_many :tags, :through => :taggings
我正在尝试创建一种简单的方法,从一个用户检索讨论中的所有标记。理想情况下,命名的_范围将被明智地使用,以保持事物的整洁。我认为应该是这样的:
tags = @discussion.tags.from_user(@user)
tags = @discussion.tags.by_user.named(@user)
在Tag类中编写这个命名的_范围是非常困难的。它应该是什么样子?我是否需要以某种方式将它与Taggings表连接起来?也许这样就可以了。但未命名\u范围解决方案:
tags = @discussion.taggings.find_by_user(@user).map(&:tag)
不确定是否需要使用
标记。请在此处按用户id(@user.id)
查找。完成后,您将得到一个数组,其中包含给定用户对给定讨论的标记。将该数组映射到taggings.tag-model(我猜您的标记模型属于一个标记)。也许这样就可以了。但未命名\u范围解决方案:
tags = @discussion.taggings.find_by_user(@user).map(&:tag)
不确定是否需要使用
标记。请在此处按用户id(@user.id)
查找。完成后,您将得到一个数组,其中包含给定用户对给定讨论的标记。将该数组映射到taggings.tag-model(我猜您的标记模型属于标记)。我还没有机会测试这个,但我认为它可能会起作用:
class Discussion < ActiveRecord::Base
has_many :taggings
has_many :tags, :through => :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :discussion
belongs_to :tag
end
class Tag < ActiveRecord::Base
has_many :taggings
has_many :discussions, :through => :taggings
named_scope :by_user do
def named(user) do
Tagging.find_by_user_and_discussion(user, discussion).tags
end
end
end
我还没有机会测试这个,但我认为它可能会起作用:
class Discussion < ActiveRecord::Base
has_many :taggings
has_many :tags, :through => :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :discussion
belongs_to :tag
end
class Tag < ActiveRecord::Base
has_many :taggings
has_many :discussions, :through => :taggings
named_scope :by_user do
def named(user) do
Tagging.find_by_user_and_discussion(user, discussion).tags
end
end
end
您确实需要以某种方式将其与taggings表连接起来。以下是方法:
class Tag < AR::Base
named_scope :from_user, lambda { |user|
{ :include => :taggings, :conditions => ["taggings.user_id = ?", user.id] }
}
end
类标记您确实需要以某种方式将其与标记表连接起来。以下是方法:
class Tag < AR::Base
named_scope :from_user, lambda { |user|
{ :include => :taggings, :conditions => ["taggings.user_id = ?", user.id] }
}
end
类标记