23

我已将 rails_admin 安装到我的应用程序中,我想做一些非常基本的事情...我有两个模型,它们的关联按预期出现...我有一个属于_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

“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

然后,我像这样更改了“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

基本上,要访问任何视图助手(制作的导轨或其他),您必须添加 indings[:view].my_tag_to_use

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

bindings[:view].rails_admin.show_path('user', user_id)
4

6 回答 6

38

我在谷歌上偶然发现了这个问题,并找到了一种更简单的方法来做到这一点。向您的模型添加titleorname方法,rails_admin 将使用该方法而不是显示“用户 #1”。

class User
  ...
  def name
    first_name + " " + last_name
  end
  ...
end

您可以使用title代替name,但在您的情况下,使用名称更有意义。

于 2014-02-03T11:44:30.197 回答
27
RailsAdmin.config {|c| c.label_methods << :full_name}

或者

config.model full_name do
  object_label_method do
    :full_name
  end
end

然后在你的模型中添加一个 full_name 方法。

于 2012-09-14T17:15:28.593 回答
10

我为“角色”模型这样做

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

def custom_label_method
  "#{role_name}"
end

有用

于 2014-04-10T13:36:23.520 回答
7

您可以使用 rails_admin object_label_method

见链接

对于用户模型,在 rails_admin.rb

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

在模型创建方法中

def custom_label_method
  "User #{user_name}"
end
于 2017-09-16T08:09:32.533 回答
2

只需将其添加到您的用户模型中:

# Prety User name display for rails_amdin
def to_s
    return self.name
end
def title
    return self.to_s
end

然后重启服务器。

您必须同时添加to_stitle方法,并且可以self.name根据用户模式中的任何内容进行更改。

它适用于 Rails 4。

于 2015-07-10T11:43:20.070 回答
0

使用像名称这样通用的东西,我通常会在模型上添加一个方法。但替代解决方案是为 RA 中的字段配置标签

于 2016-01-13T01:38:44.750 回答