Nested forms in rails - accessing attribute in has_many relation

后端 未结 4 993
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 03:06

I have a user and a profile model. One user can have many profiles. I need to access only one information from the profiles section (viz the phone number) in my user model d

相关标签:
4条回答
  • 2020-12-09 03:19

    You can use 'accepts_nested_attributes_for' to do this; but there's a little trick in forms:

    You must use the singular, and call fields_for for each profile, like this:

    <% form_for @user do |f| -%>
    <% @user.profiles.each do %>
    <% f.fields_for :profile_attributes, profile do |ff| -%>
    <% end %>
    

    Notice that is :profile_attributes, instead of just :profile.

    0 讨论(0)
  • 2020-12-09 03:31

    You could do something like the following:

    <% form_for @user, :url => { :action => "update" } do |user_form| %>
      ...
      <% user_form.fields_for :profiles do |profiles_fields| %>
         Phone Number: <%= profiles_fields.text_field :profile_mobile_number %>
       <% end %>
    <% end %>
    

    But since you already have an association, then might as well use 'accepts_nested_attributes_for'

    0 讨论(0)
  • 2020-12-09 03:31

    You should watch RailsCasts Nested Model Form.
    thanks Ryan Bates great work.

    0 讨论(0)
  • 2020-12-09 03:36

    http://apidock.com/rails/v3.2.8/ActionView/Helpers/FormHelper/fields_for

    This api dock link list many Nested Attributes Examples including one-to-one, one-to-many. It's very helpful!

    0 讨论(0)
提交回复
热议问题