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

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

问题描述

如何实现以下功能?我有两个模型(博客和读者)和一个JOIN表,将允许我们之间有一个N:M的关系:

  class Blog< ActiveRecord :: Base 
has_many:blogs_readers,:dependent => :destroy
has_many:reader,: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 表。第二个问题是,如何获取读者未订阅的博客列表(例如,填写下拉菜单)

解决方案

如何:

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

Rails通过关联方法来处理我们的ids集合! :)



http: //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html


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

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)?

解决方案

What about:

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

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

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

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

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