Martin
Martin

Reputation: 11336

parent Form nested Rails

I have a Subscription model nested to a User model.

I'm trying to create a form to add new subscriptions under /subscriptions/new

The fields that appears on this form are saved in the parent User model.

In my new action I simply have

@subscription = Subscription.new

Question is how to add the fields of this parent User inside the subscriptions new form_for? The subscription form somehow its the nested of a parent.

Upvotes: 1

Views: 264

Answers (1)

Justin
Justin

Reputation: 1203

It would be very helpful if you included the code from your User and Subscription models to your answer, so that we can see the relationships. Based on your comments, it sounds like you are doing the following:

class User < ActiveRecord::Base
  has_many :subscriptions
  accepts_nested_attributes_for :subscription 
end

class Subscription < ActiveRecord::Base
  belongs_to :user
end

It sounds like you want to capture data for users and subscriptions in the same form. To do so you would have to nest the forms, using fields_for on the nested form (note the accepts_nested_attributes_for above.

<%= form_for @user do |user_form|%> 
  <%= user_form.text_field :phone %>
  <%= user_form.fields_for :subscription @user.subscription.new do |subscription_form|%>
    <%= subscription_form.text_field :name %>
  <% end %>
<% end %>

Then, in your create method in your controller, you can simply call:

@user = User.create(params[:user])

This code isn't tested, and I'm making a lot of assumptions about your setup, but hopefully this will be enough to get you started. For more information, the docs on fields_for are here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for

Upvotes: 1

Related Questions