Ruby on rails 在这种情况下,我如何设置“has_many”条件?
使用者 -上次活动时间(上次登录时间) 社区 -用户id 代码 -用户id -社区idRuby on rails 在这种情况下,我如何设置“has_many”条件?,ruby-on-rails,ruby-on-rails-3,activerecord,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 3,Activerecord,Ruby On Rails 4,使用者 -上次活动时间(上次登录时间) 社区 -用户id 代码 -用户id -社区id 用户拥有许多社区和代码 社区属于用户,有很多代码 代码属于用户和社区 型号/用户.rb has_many :communities has_many :codes, :dependent => :destroy belongs_to :user, counter_cache: true has_many :codes belongs_to :user, counter_cache: true be
has_many :communities
has_many :codes, :dependent => :destroy
belongs_to :user, counter_cache: true
has_many :codes
belongs_to :user, counter_cache: true
belongs_to :community, counter_cache: true
模型/社区.rb
has_many :communities
has_many :codes, :dependent => :destroy
belongs_to :user, counter_cache: true
has_many :codes
belongs_to :user, counter_cache: true
belongs_to :community, counter_cache: true
型号/代码.rb
has_many :communities
has_many :codes, :dependent => :destroy
belongs_to :user, counter_cache: true
has_many :codes
belongs_to :user, counter_cache: true
belongs_to :community, counter_cache: true
我可以通过使用名为“acts_as_votable”的gem这样编码来检索所有社区()
然后我试图检索那些all@communities下的所有代码
@codes = Code.includes(:user).where(:community_id => @communities.collect(&:id)).order('created_at DESC').page(params[:page]).per(10)
但我想按用户表的最后一个活动列在
列对其排序。
所以我在下面试了一下
@codes = Code.includes(:user).where(:community_id => @communities.collect(&:id)).order("users.last_active_at DESC").page(params[:page]).per(10)
但它需要永远加载
最好的解决方案可能是通过代码在社区和用户之间创造许多条件吗?
那么应该是这样的
@codes = @communities.code_group.include(:users).order("users.last_active_at DESC").page(params[:page]).per(10)
如何更改代码?我认为您需要通过::communities将
用户
模型上的has\u many
更改为has\u many code>。那么code
应该只属于:社区
。这是除非用户
可以拥有代码
,而代码
不与社区关联
如果用户不属于社区但拥有该社区的代码怎么办?不属于你的意思是数据库中没有该用户/社区组合的记录?不。用户可以属于社区,它是通过使用我在问题中提到的称为“acts_as_votable”的gem来处理的。所以它与代码表完全分离。