如何将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 %>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...