has_many通过关联wice_grid

时间:2013-07-06 16:47:44

标签: ruby-on-rails ruby-on-rails-3 has-many-through

我正在尝试使用wice_grid gem

来获取用户在网格表中的角色
user has_many :roles, :through => :assignments

role has_many :users, :through => :assignments

在users_controller.rb

@users_grid = initialize_grid(User,
                                  :include => [:assignments, :roles])

我应该在视图中写什么才能让用户的角色出现,我不能从文档中获取它所以需要帮助请如何在视图中编写它?

1 个答案:

答案 0 :(得分:2)

试试以下内容。 let name是users表中的列,role_name是roles表中的列。

<%= grid(@users_grid) do |g|
  # Here I have defined the column name. Column names are defined with parameter ':name' and the ':attribute' defines which column to map in the users table for this column.
  g.column :name => 'User Name', :attribute => 'name' do |user|  # primary table
    link_to(user.name, user_path(user))
  end

  # Regarding join tables or associations, we need to specify the model name as here, I have defined model: 'Role'.
  g.column name: 'Having Roles', attribute: 'role_name', model: 'Role' do |user|
    # here we are using the associations showing the data for the joints table.
    user.roles.collect{|role| role.role_name}.to_sentence
  end

  g.column do |user|
    link_to('Edit', edit_user_path(user))
  end
end%>

您可以查看示例示例https://github.com/leikind/wice_grid_testbed

的代码