一个困难的named_scope情况
在我的应用程序中,用户可以开始并参与讨论。 他们还可以标记讨论; 当他们这样做时,会创建一个包含标签名称的标签(如果它尚不存在),并且还会创建一个标记,它会记住哪个用户用哪个标签标记了哪个讨论。
因此,在讨论模型中,我们有这样的内容:
has_many :taggings
has_many :tags, :through => :taggings
我正在尝试创建一种简单的方法来检索一个用户讨论中的所有标签。 理想情况下,明智地使用named_scopes 可以使事情保持美观和干净。 我认为它应该看起来像这样:
tags = @discussion.tags.from_user(@user)
在 Tag 类中编写这个named_scope 变得非常困难。 它应该是什么样子? 我需要以某种方式将其与标签表连接起来吗?
In my application, Users can start and participate in Discussions. They can also Tag Discussions; when they do so, a Tag is created containing the name of the tag (if it didn't already exist), and a Tagging, which remembers which User tagged which Discussion with what Tag, is created too.
So inside the Discussion model we have this:
has_many :taggings
has_many :tags, :through => :taggings
I'm trying to create an easy way to retrieve all the Tags on a Discussion from one User. Ideally, named_scopes would be used judiciously to keep things nice and clean. I think it should look something like this:
tags = @discussion.tags.from_user(@user)
Writing this named_scope inside the Tag class is turning out to be very difficult. What should it look like? Do I need to join it with the Taggings table somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您确实需要以某种方式将其与标签表连接起来。 就是这样:
You do need to join it with the taggings table somehow. Here's how:
也许这会做到。 但不是named_scope解决方案:
不确定您是否需要在此处使用
taggings.find_by_user_id(@user.id)
。 完成后,您将得到一个数组,其中包含给定用户的给定讨论的标签。 将该数组映射到 taggings.tag-model (我猜您的标记模型属于标签)。Maybe this will do it. Not named_scope solution though:
Not sure if you need to use
taggings.find_by_user_id(@user.id)
here. When that is done, you'll be left with an array which includes the taggings on given discussion by given user. Map that array to taggings.tag-model (I guess your Tagging model belongs_to a Tag).我还没有机会测试这个,但我认为它可能会起作用:
像这样使用它:
I haven't had chance to test this, but I think it might work:
Use it like this: