我有以下ActiveAdmin模型
class AdminUser < ActiveRecord::Base
has_many :challenges
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
end
以及以下挑战模型
class Challenge < ActiveRecord::Base
belongs_to :subdomain
belongs_to :admin_user
has_many :comments, :dependent => :destroy
end
我在application.html.erb中定义了以下方法
helper_method :all_admin_users
def all_admin_users
@users = AdminUser.all
end
Adminuser具有以下属性:id,:name,:email 现在,当我尝试访问特定用户的挑战时
<ul>
<% all_admin_users.each do |user| %>
<li> <%= link_to user.name ,user.challenges%></li>
<br />
<% end %>
</ul>
我收到以下错误&#34;未定义的方法`to_model&#39; for Challenge :: ActiveRecord_Associations_CollectionProxy
这是我的routes.rb文件
Rails.application.routes.draw do
resources :comments
devise_for :admin_users, ActiveAdmin::Devise.config
get 'subdomains/index'
get 'subdomains/edit'
get 'subdomains/new'
get 'subdomains/show'
get 'home/index'
root 'home#index'
resources :challenges
resources :subdomains
ActiveAdmin.routes(self)
end
答案 0 :(得分:1)
首先在routes
文件中,您需要添加操作以列出用户挑战的
在routes.rb
末尾添加
get 'users/:user_id/challenges' => 'challenges#user_challenges', as: :user_challenges
# this way you will have action to view users challenges
# inside your challenges controller
在challenges_controller.rb
添加操作user_challenges
def user_challenges
@challenges = Challenge.where(admin_user_id: params[:user_id])
end
为此操作创建视图,并显示您的挑战
然后您可以为此操作创建链接
<ul>
<% all_admin_users.each do |user| %>
<li> <%= link_to user.name , user_challenges_path(user.id)%> </li>
<br />
<% end %>
</ul>
答案 1 :(得分:1)
而不是user.challenges
使用user.challenge
<强>更新强>
<ul>
<% all_admin_users.each do |user| %>
<% user.challenges.each do |challenge| %>
<li> <%= link_to user.name ,challenges_path(user_id: user.try(:id)) %></li>
<br />
<% end %>
<% end %>
</ul>
challenges_controller.rb
def index
@challenges = Challenge.where(admin_user_id: params[:user_id])
end
答案 2 :(得分:0)
作为Prashant4020答案的补充 - 您对更新用户模型的看法:
class User < ActiveRecord::Base
...
belongs_to :admin_user
...
因此
class AdminUser < ActiveRecord::Base
has_many :challenges
has_many :users
....