Ruby on rails Rails表单:与属于另一个的字段\u进行多态关联的字段\u
我在一个叫做“病人”的模型上有一个表单,它通过多态关联有一个“角色”。“角色”有一个“用户”。我需要通过表单修改“用户”字段“名字”Ruby on rails Rails表单:与属于另一个的字段\u进行多态关联的字段\u,ruby-on-rails,Ruby On Rails,我在一个叫做“病人”的模型上有一个表单,它通过多态关联有一个“角色”。“角色”有一个“用户”。我需要通过表单修改“用户”字段“名字” class Patient < ApplicationRecord has_one :role, :as => :roleable, dependent: :destroy accepts_nested_attributes_for :role end class Role < ApplicationRecord bel
class Patient < ApplicationRecord
has_one :role, :as => :roleable, dependent: :destroy
accepts_nested_attributes_for :role
end
class Role < ApplicationRecord
belongs_to :user
accepts_nested_attributes_for :user
belongs_to :roleable, polymorphic: true, optional: true
end
class User < ApplicationRecord
has_many :roles
end
class PatientsController < ApplicationController
def show
@patient = Patient.find(params[:id])
# This works just fine, so I know the data is there
puts(@patient.role.user.first_name)
end
end
分类患者:rolable,dependent::destroy
接受:角色的\u嵌套\u属性\u
结束
类角色<应用程序记录
属于:用户
接受用户的\u嵌套\u属性\u
属于:Rolable,多态:true,可选:true
结束
类用户<应用程序记录
有很多:角色
结束
类PatientsController<应用程序控制器
def秀
@patient=patient.find(参数[:id])
#这很好,所以我知道数据就在那里
放置(@patient.role.user.first_name)
结束
结束
如何制作包含此字段的表单?这是我目前为止没有用的:
<%= form_for(:patient, url: edit_patient_path(params[:id])) do |f| %>
<%= f.fields_for :role do |r| %>
<%= r.fields_for :user do |u| %>
<%= u.text_field :first_name, value: u.first_name, class: "value", disabled: false %>
<% end %>
<% end %>
<% end %>
undefined method `first_name' for #<ActionView::Helpers::FormBuilder:0x007f82d30c4ad8>
但不幸的是,这不起作用:
<%= form_for(:patient, url: edit_patient_path(params[:id])) do |f| %>
<%= f.fields_for :role do |r| %>
<%= r.fields_for :user do |u| %>
<%= u.text_field :first_name, value: u.first_name, class: "value", disabled: false %>
<% end %>
<% end %>
<% end %>
undefined method `first_name' for #<ActionView::Helpers::FormBuilder:0x007f82d30c4ad8>
未定义的方法“first\u name”#
首先将表单更改为
,以便它包装@patient对象
使用.object
将对象包装到表单生成器中
<%= u.text_field :first_name, value: u.object.first_name, class: "value", disabled: false %>
但您不需要在第一个位置显式指定值,禁用的属性默认为false:
<%= u.text_field :first_name, class: "value" %>
你说的不工作是什么意思?是否有任何错误消息?有日志显示了什么吗?抱歉,更新了。啊,你应该使用
而不是:患者。看,是的。。。这就解决了问题。我需要查找原因,以及在创建表单时使用@patient或:patient的区别,因为我看到的所有内容都显示总是使用:patient我想我现在明白了patient用于创建新患者,其中更新现有患者时需要使用as@patient。有点-最好对这两种情况都使用
,并在控制器中设置@patient=patient.new
,因为它允许您使用完全相同的视图。甚至
也更好。对于Rails 5.1+,您希望使用表单与(model:@patient)