Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在这种情况下,我如何设置“has_many”条件?_Ruby On Rails_Ruby On Rails 3_Activerecord_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 在这种情况下,我如何设置“has_many”条件?

Ruby 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

使用者 -上次活动时间(上次登录时间)

社区 -用户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
    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来处理的。所以它与代码表完全分离。