I have what I hope to be a simple question. I need to display the value for an attribute on the Edit page, while keeping the input field for the same attribute. How might this be accomplished?
Well generally you can just use the original object, like you'll have an @foo
that you'll have used in your form_for
statement, so you can just use that directly: = @foo.the_attribute
If you're within a partial, or elsewhere where you have only the form builder instance, then you can refer to the underlying object with the .object
method, eg.:
= form_for @foo do |f|
# in here, f.object == @foo
In my case, I'm working with accepts_nested_attributes_for
in two models. Event
accept nested objects from Speaker
. And Speaker
has a perfil_id
attribute which could be ['Maker', 'Developer', 'Entrepreneur', ...] .
The Speaker
's form is a partial rendered from the principal form, Event
's form:
<%= 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 %>
Partial
<%= 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' %>
When editing Event's Speakers I wanted a select_tag
to select the profile name for the actual Speaker.
I could not use an input field for this. So I need to get the correct values from the builder object and I get what I need by doing this:
f.object.profile_id
Passing it as a fourth param to the select options
I get this working:
<% options = options_from_collection_for_select(@profiles, 'id', 'name', f.object.profile_id ) %>
I hope it could be useful for you too!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.