如何避免重复的has

编程入门 行业动态 更新时间:2024-10-07 22:20:11
本文介绍了如何避免重复的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/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! :)

api.rubyonrails/classes/ActiveRecord/Associations/ClassMethods.html

更多推荐

如何避免重复的has

本文发布于:2023-08-03 14:44:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287749.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!