will_paginate - 协会

时间:2014-05-18 14:14:27

标签: ruby-on-rails ruby-on-rails-4 associations will-paginate

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

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

<% @alliance.players.each do |p| %>
  <% p.towns.each do |t| %>
    ...
  <% end %>
<% end %>

我在说什么:

Alliance ->
  Players ->
    Towns <--

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

也许有更好的方法可以做到这一点。


协会:

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

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

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

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

所以我可以打电话给@alliance_towns.each do {}但是我正在接受

undefined method `towns' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Player:0x007f9268d91348>

我缺少什么?

1 个答案:

答案 0 :(得分:5)

您应该使用join。像这样:

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