从Rails表单构建器获取数据属性值,而不使用输入字段

我有我希望成为一个简单的问题。 我需要在Edit页面上显示属性的值,同时保持相同属性的输入字段。 这怎么可能实现?

通常你可以使用原始对象,就像你将在form_for语句中使用@foo一样,所以你可以直接使用它: = @foo.the_attribute

如果您在部分或其他只有表单构建器实例的区域内,则可以使用.object方法引用基础对象,例如:

 = form_for @foo do |f| # in here, f.object == @foo 

就我而言,我在两个模型中使用accepts_nested_attributes_forEvent接受来自Speaker嵌套对象。 而且Speaker有一个perfil_id属性,可以是[‘Maker’,’Developer’,’Entrepreneur’,…]

Speaker者的表格部分由主要表格, Event的forms呈现:

 <%= form_for(event) do |f| %> <%= f.text_field :title %> <%= f.label :title, 'Event name' %> <%= f.fields_for :speakers do |builder| %> <%= render 'events/partials/speaker_fields', f: builder %> <% end %> <%= f.submit %> <% end %> 

局部

 <%= builder.number_field :name %> <%= builder.label :name %> <% options = options_from_collection_for_select(@profiles, 'id', 'name', f.object.member_profile_id ) %> <%= select_tag "event[speakers_attributes][profile_id]", options, prompt: 'Select a Profile' %> 

编辑 Event’s Speakers时,我想要一个select_tag来选择实际Speaker的配置文件名称。

我无法使用输入字段 。 所以我需要从构建器对象中获取正确的值,并通过这样做得到我需要的东西:

f.object.profile_id

将它作为第四个参数传递给select options我得到了这个工作:

<% options = options_from_collection_for_select(@profiles, 'id', 'name', f.object.profile_id ) %>

我希望它对你也有用!