如何将text_method或label_method代码从模型移动到视图

问题描述

我目前正在这样做

class User < ApplicationRecord
  has_many :courses,dependent: :destroy
end

class Course < ApplicationRecord 
  belongs_to :user
  def title_with_username
    "#{title} by #{user.username}"
  end 
end

<%= simple_form_for @tag do |f| %>
    <%= f.input :category_id,collection: Category.all %>
    <%= f.input :course_id,collection: Course.all,label_method: :title_with_username,value_method: :id %>
    <%= f.button :submit %>
<% end %>

是否可以在不触摸模型的情况下在视图中全部执行label_method?

解决方法

您可以将现有的select标签转换为类似

<%= f.input :course_id,collection: Course.all.map {|c| [c.id,"#{c.title} by #{c.user.username}"]} %>

您可以在控制器中构建此集合数组,并在此处传递,因为视图不会不必要地混乱。

,

我不完全理解为什么,但这似乎可行

<%= f.input :course_id,collection: Course.all,label_method: lambda { |course| "#{course.title} by #{course.user.username}" },value_method: :id %>