1

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.

6
  • Do you want the users to edit the User too? Commented May 17, 2012 at 19:25
  • No. actually they don't edit the subscription either. Commented May 17, 2012 at 19:35
  • Okay. I don't understand why you are talking about the "parent" while the subscription isn't even created. Can you explain please? Commented May 17, 2012 at 19:37
  • That's true. The parent is the User model. Since the User may have different subscriptions I was thinking to create the User together with the subscription and send the phone to the User which is the only value stored on the user. Commented May 17, 2012 at 19:46
  • Then you have to create the "subscription in the user form", not the "user in the subscription form", since the user is the parent. Am I right? Commented May 17, 2012 at 19:49

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.