Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How to save nested attribute in existing records?


  • Please log in to reply
1 reply to this topic

#1 andrewliu

andrewliu

    Signalman

  • Members
  • 17 posts

Posted 13 October 2013 - 01:09 AM

I have nested attributes under my user's view and would like to update nested attribute information based on existing record, but not sure how to do so. Its just added a new record.

 

I have this in my view

<%= form_for @user, :html => {:multipart => true} do |f| %>
  <%= f.text_field :company_name %>
  <%= f.fields_for :businesses do |biz| %>
    <%= biz.text_field :street %>
    <%= biz.text_field :city %>
    <%= biz.text_field :zip %>
  <% end %>
<% end %>

Then I have this in my controller:

  def edit
    @user = User.find(current_user.id)
    @user.businesses.new if @user.businesses.empty?
  end 

  def update
    @biz = Business.find_or_create_by_name(params[:user][:company_name])
  end

So the update method allows the "company_name" to be saved in the "Business" table as well. But now I'd like to get the street, city, and zip in that business record. 

 

I think I have to get the business id and then update the record based on that id?



#2 Jamie

Jamie

    Controller

  • Moderators
  • 114 posts
  • LocationThe UK

Posted 13 October 2013 - 09:18 AM

Hello :)

 

I would start off by adding 

accepts_nested_attributes_for :businesses

to the User model.

 

I would then inside of the params (assuming you're in favour of using Rails 4 Strong Parameters) the following:

params.require(:user).permit(:field1, :field2, :field3, :business_attributes [:field1, :field2, :field3, :etc]) 

At least that's how I understand it.

 

Hope this is some help...


Rails developer based in Newcastle, UK.
Web app owner - Twitter lover




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users