如何实现以下功能?我有两个模型(博客和读者)和一个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/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 endWhat 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! :)
api.rubyonrails/classes/ActiveRecord/Associations/ClassMethods.html
更多推荐
如何避免重复的has
发布评论