will_paginate - 协会

Min*_*ohn 2 ruby-on-rails associations will-paginate ruby-on-rails-4

我正在尝试对一个协会进行分页,但我错过了一些东西.

这是我需要分页的地方.paginate(:page => params[:page], :per_page => 25).如果我理解正确,我必须在我的控制器中创建一个变量来取城镇?

<% @alliance.players.each do |p| %>
  <% p.towns.each do |t| %>
    ...
  <% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

我在说什么:

Alliance ->
  Players ->
    Towns <--
Run Code Online (Sandbox Code Playgroud)

基本上我坚持如何在二级循环中对关联进行分页.

也许有更好的方法来做到这一点.


协会:

class Alliance < ActiveRecord::Base
  # Primary Key
  self.primary_key = 'grepo_id'

  # Associations
  has_many :players
end


class Player < ActiveRecord::Base
  # Primary Key
  self.primary_key = 'grepo_id'

  # Associations
  has_many :towns
  belongs_to :alliance    
end

class Town < ActiveRecord::Base
  # Primary Key
  self.primary_key = 'grepo_id'

  # Associations
  belongs_to :player, :foreign_key => :player_id
end
Run Code Online (Sandbox Code Playgroud)

我已经尝试过很多但是没有找到任何解决方案.

我试图在我的控制器中创建一个变量:

@alliance_towns = @alliance.players.towns.order("rank ASC").paginate(:page => params[:page], :per_page => 25)
Run Code Online (Sandbox Code Playgroud)

所以我可以打电话,@alliance_towns.each do {}但就此而言,我正在接受

undefined method `towns' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Player:0x007f9268d91348>
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Mis*_*cha 5

你应该使用一个联接.像这样的东西:

@alliance_towns = Town.joins(:player).where('players.alliance_id = ?', params[:id]).order('rank ASC').paginate(:page => params[:page], :per_page => 25)
Run Code Online (Sandbox Code Playgroud)