简体   繁体   English

使用:has_many关联和多个条件查找

[英]Find using :has_many associations and multiple conditions

In my application, Users view Pins which I store in a separate associations table called View. 在我的应用程序中,“用户”查看我存储在称为“视图”的单独关联表中的引脚。 The table has an ID, a pin_id, a user_id and a rank. 该表具有ID,pin_id,user_id和等级。 I would like to find Pins which meet certain criteria which the user has not seen. 我想找到符合用户未曾看到的某些标准的引脚。 I am using Rails 3.2.13. 我正在使用Rails 3.2.13。

Here are my model associations: 这是我的模型关联:

class Pin
has_many :views
has_many :users, :through => :views

class View
belongs_to :pin
belongs_to :user

class User
has_many :pins
has_many :views  
has_many :pins, :through => :views

Right now I am doing this, which works: 现在,我正在这样做,它的工作原理是:

pins_controller.rb pins_controller.rb

b = TRUE
sex = current_user.sex
views = current_user.views
seen = views.map(&:pin_id)
@pins = Pin.find(:first, :conditions => ["sex = ? AND active = ? AND id not in (?)", sex, b, seen])

I thought it would be more elegant to use a join to pull the objects using a single database query. 我认为使用联接通过单个数据库查询拉取对象会更优雅。 However, I cannot get this to work. 但是,我无法使它正常工作。 I have read a bunch of different SO articles, but I have not been able to reproduce the above using a single query. 我读了许多不同的SO文章,但是我无法使用单个查询来重现以上内容。 Am I correct in thinking the above is roundabout and that there is a better way? 我以为上述是环形交叉路口并且有更好的方法吗?

You should be able to just join up pins to view and view to users . 您应该只需要连接pins即可viewview users I think the below will work, although would need the specific details on the view to users association: 我认为以下内容将起作用,尽管需要与users关联view上的特定详细信息:

Pin.joins(:views => :user).where("views.sex = ? and views.active = ? and users.id not in (?)", current_user.sex, true, [current_user.id])

Try squeel its wounderful and more better than normal active Record query methods and give you more powerful features 尝试缓解其创伤,并且比普通的Active Record查询方法更好,并为您提供更强大的功能

https://github.com/activerecord-hackery/squeel https://github.com/activerecord-hackery/squeel

http://railscasts.com/episodes/354-squeel http://railscasts.com/episodes/354-squeel

You could do something like this: 您可以执行以下操作:

Pin.joins(:views).where(sex: sex, active: b).
  merge(View.where(View.arel_table[:user_id].not_eq(current_user.id))).first

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM