考虑一个简单的关联......
class Person
has_many :friends
end
class Friend
belongs_to :person
end
Run Code Online (Sandbox Code Playgroud)
让所有在ARel和/或meta_where中没有朋友的人最简洁的方法是什么?
然后是一个has_many:通过版本
class Person
has_many :contacts
has_many :friends, :through => :contacts, :uniq => true
end
class Friend
has_many :contacts
has_many :people, :through => :contacts, :uniq => true
end
class Contact
belongs_to :friend
belongs_to :person
end
Run Code Online (Sandbox Code Playgroud)
我真的不想使用counter_cache - 而且我从我读过的内容中看起来并不适用于has_many:通过
我不想拉出所有的person.friends记录并在Ruby中循环它们 - 我希望有一个可以与meta_search gem一起使用的查询/范围
我不介意查询的性能成本
离实际的SQL越远越好......
我正在开发一个允许会员进行调查的应用程序(会员与Response有一对多的关系).Response保存member_id,question_id及其答案.
调查全部或全部提交,因此如果该成员的响应表中有任何记录,则他们已完成调查.
我的问题是,如何重新编写下面的查询,以便它实际工作?在SQL中,这将是EXISTS关键字的主要候选者.
def surveys_completed
members.where(responses: !nil ).count
end
Run Code Online (Sandbox Code Playgroud) 我找到了一个答案,其中有一些可用的having例子可以找到有n孩子的父母,但同样不能用于找到没有孩子的父母(大概是因为连接不包括他们).
scope :with_children, joins(:children).group("child_join_table.parent_id").having("count(child_join_table.parent_id) > 0")
Run Code Online (Sandbox Code Playgroud)
谁能指出我正确的方向?
如果我有一个模型Person,has_many Vehicles每个模型都Vehicle可以是类型,car或者motorcycle我如何查询所有拥有汽车的人和所有拥有摩托车的人?
我不认为这些是正确的:
Person.joins(:vehicles).where(vehicle_type: 'auto')
Person.joins(:vehicles).where(vehicle_type: 'motorcycle')
Run Code Online (Sandbox Code Playgroud) 我的模特在这里:
class User < ActiveRecord::Base
has_many :bookmarks
end
class Topic < ActiveRecord::Base
has_many :bookmarks
end
class Bookmark < ActiveRecord::Base
belongs_to :user
belongs_to :topic
attr_accessible :position
validates_uniqueness_of :user_id, :scope => :topic_id
end
Run Code Online (Sandbox Code Playgroud)
我想topics用current_user相关的for 来获取所有内容bookmark.ATM,我这样做:
Topic.all.each do |t|
bookmark = t.bookmarks.where(user_id: current_user.id).last
puts bookmark.position if bookmark
puts t.name
end
Run Code Online (Sandbox Code Playgroud)
这很难看并且做了太多的数据库查询.我想要这样的东西:
class Topic < ActiveRecord::Base
has_one :bookmark, :conditions => lambda {|u| "bookmarks.user_id = #{u.id}"}
end
Topic.includes(:bookmark, current_user).all.each do |t| # this must also includes topics without bookmark …Run Code Online (Sandbox Code Playgroud)