如何避免 has_many :through 关系中的重复? [英] how to avoid duplicates in a has_many :through relationship?

查看:18
本文介绍了如何避免 has_many :through 关系中的重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能实现以下目标?我有两个模型(博客和读者)和一个 JOIN 表,可以让我在它们之间建立 N:M 关系:

How can I achieve the following? I have two models (blogs and readers) and a JOIN table that will allow me to have an N:M relationship between them:

class Blog < ActiveRecord::Base
  has_many :blogs_readers, :dependent => :destroy
  has_many :readers, :through => :blogs_readers
end

class Reader < ActiveRecord::Base
  has_many :blogs_readers, :dependent => :destroy
  has_many :blogs, :through => :blogs_readers
end

class BlogsReaders < ActiveRecord::Base
  belongs_to :blog
  belongs_to :reader
end

我现在想做的是将读者添加到不同的博客.但是,条件是我只能将读者添加到博客一次.所以 BlogsReaders 表中不能有任何重复项(相同的 readerID、相同的 blogID).我怎样才能做到这一点?

What I want to do now, is add readers to different blogs. The condition, though, is that I can only add a reader to a blog ONCE. So there mustn't be any duplicates (same readerID, same blogID) in the BlogsReaders table. How can I achieve this?

第二个问题是,我如何获得读者尚未订阅的博客列表(例如,填写下拉选择列表,然后可以使用该列表将读者添加到另一个博客)?

The second question is, how do I get a list of blog that the readers isn't subscribed to already (e.g. to fill a drop-down select list, which can then be used to add the reader to another blog)?

推荐答案

怎么样:

Blog.find(:all,
          :conditions => ['id NOT IN (?)', the_reader.blog_ids])

Rails 通过关联方法为我们处理 id 的收集!:)

Rails takes care of the collection of ids for us with association methods! :)

http://api.rubyonrails.org/classes/ActiveRecord/Associations/类方法.html

这篇关于如何避免 has_many :through 关系中的重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆