LearningRoR
LearningRoR

Reputation: 27242

Create Child only and select a Parent in nested form?

Instead of creating a new Parent and also creating the children. Is it possible to select from a list of Parents and then only create the children that are assigned to a current user and that specific Survey?

Lets use this example:

class Survey < ActiveRecord::Base
  has_many :questions
  accepts_nested_attributes_for :questions
end

class Question < ActiveRecord::Base
  belongs_to :survey
  belongs_to :user
end

And then in the controller:

def new
  # @survey = select menu of all Surveys
  3.times do
    question = @survey.questions.build
  end
end

def create
 # Saves new questions with current user
 if @survey.save
   flash[:notice] = "Success"
   redirect_to @survey
 else
   render :action => 'new'
 end
end

I'm not sure what the create and new actions would turn into. Any idea?

Upvotes: 0

Views: 772

Answers (1)

Andre Bernardes
Andre Bernardes

Reputation: 1623

You can call the edit action on a existing survey passing the selected survey to it:

edit_survey_path(@survey)

Then you can load the selected survey in that action:

def edit
  @survey = Survey.find(params[:id])
end

In the edit view, use a nested form to add/delete questions, and then, in the update action, updating your surveys attributes will also add and delete the questions.

def update
  @survey = Survey.find(params[:id])
  @survey.update_attributes(params[:survey])
  redirect_to ...
end

All of this will work assuming you've set accepts_nested_attributes_for :questions in the survey model.

My answer here is a summary of Ryan Bates' screencast on nested forms which I think you've already seen, based on the similarity of your example and his.

What I'd like to point out here is that you can achieve what you want using exactly the same code, however using the edit/update actions on your parent model instead of new/create on the child model.

Edit:

In order to assign the current user to a survey question, do the explicit assignment in the new and edit action:

def new
  @survey = Survey.new
  3.times do
    question = @survey.questions.build(:user_id => current_user.id)
  end
end

def edit
  # find the preselected Survey...
  @survey = Survey.find(params[:id])

  # This adds a (one) new empty question, consider doing it via Javascript
  # for adding multiple questions.
  @survey.questions.build(:user_id => current_user.id)
end

In your form for questions, add:

<%= form_builder.hidden_field :user_id %>

Don't forget to replace form_builder with your actual form builder object.

Now all the new questions will be assigned to the current user because the current user was submitted by the form along with the other attributes for questions.

Upvotes: 1

Related Questions