rails_admin显示名称而不是id

use*_*082 23 ruby-on-rails-3 rails-admin

我已经将rails_admin安装到我的应用程序中,我想要做一些非常基本的事情...我有两个模型,他们的关联按预期出现...我有一个研讨会注册模型belongs_to:user.

在rails_admin中,它将我的研讨会注册用户列为用户#1,用户#1等.

我想让它成为用户的名字.我设法做的是:

config.model SeminarRegistration do
label "Seminar Signups"
# Found associations:
  configure :user, :belongs_to_association 
  configure :seminar_time, :belongs_to_association   #   # Found columns:
  configure :id, :integer 
  configure :user_id, :integer         # Hidden 
  configure :seminar_time_id, :integer         # Hidden 
  configure :created_at, :datetime 
  configure :updated_at, :datetime   #   # Sections:

list do
  field :user do
    pretty_value do
     user = User.find(bindings[:object].user_id.to_s)
     user.first_name + " " + user.last_name
    end
  end
  field :seminar_time
end
export do; end
show do; end
edit do; end
create do; end
update do; end
end
Run Code Online (Sandbox Code Playgroud)

"pretty_value"部分为我提供了我的用户名和姓的文本......但有两个问题:

1)它不再是一个链接.如果我保留默认值(用户#1,用户#2等),它会提供指向该用户的链接.我该如何获得该链接?rails_admin如何定义它的路径?

2)似乎非常笨拙,不得不在我的形式中通过id查找...

对不起,如果这是一个基本问题.我已经阅读了手册并查找了其他问题,但它还没有完全"点击"给我.我对rails也很陌生.

谢谢.


我必须这样做才能使用链接:

我按照建议为全名添加了一个帮助方法,但是将它保存在我的视图助手中:

module ApplicationHelper
 def full_name(user_id)
  user = User.find(user_id)
  user.first_name + " " + user.last_name
 end
end
Run Code Online (Sandbox Code Playgroud)

然后,我改变了"pretty_value"部分,如下所示:

pretty_value do
  user_id = bindings[:object].user_id
  full_name = bindings[:view].full_name(user_id)
  bindings[:view].link_to "#{full_name}", bindings[:view].rails_admin.show_path('user', user_id)
end
Run Code Online (Sandbox Code Playgroud)

基本上,要访问任何视图帮助程序(使用rails或其他),您必须添加indings [:view] .my_tag_to_use

要获取用户的rails_admin路由,例如,您可以执行以下操作:

bindings[:view].rails_admin.show_path('user', user_id)
Run Code Online (Sandbox Code Playgroud)

小智 37

我在谷歌上偶然发现了这个问题,并找到了一种更简单的方法.在模型中添加一个titlename方法,rails_admin将使用它而不是显示"User#1".

class User
  ...
  def name
    first_name + " " + last_name
  end
  ...
end
Run Code Online (Sandbox Code Playgroud)

您可以使用title而不是name,但在您的情况下,使用名称更有意义.


Ben*_* B. 25

RailsAdmin.config {|c| c.label_methods << :full_name}
Run Code Online (Sandbox Code Playgroud)

要么

config.model full_name do
  object_label_method do
    :full_name
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在模型中添加full_name方法.


May*_*ank 10

我喜欢"角色"模型

config.model 'Role' do
  object_label_method do
    :custom_label_method
  end
end

def custom_label_method
  "#{role_name}"
end
Run Code Online (Sandbox Code Playgroud)

有用


小智 7

您可以使用 rails_admin object_label_method

见链接

对于用户模型,在 rails_admin.rb

config.model 'User' do
  object_label_method do
   :custom_label_method
  end
end
Run Code Online (Sandbox Code Playgroud)

在模型创建方法中

def custom_label_method
  "User #{user_name}"
end
Run Code Online (Sandbox Code Playgroud)