felix
felix

Reputation: 77

rails update and create 2 models in one form_for

I am using rails cast 196 ( http://railscasts.com/episodes/196-nested-model-form-revised?autoplay=true ) to help me on my project, I am trying to modify the code so that when I make a new question, I am able to change the survey's title in the form. right now the form submits but no change is made to the Survey's title in the db

class Survey < ActiveRecord::Base
  has_many :questions
end

I moved the accepts_nested_attributes_for from the Survey to the Question model

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

I added the :title (the field that I want to modify) in the questions pramas

def create
    @question = Question.new(question_pramas)
end

def question_pramas
    params.require(:question).permit(:content, survey_attribute: :title)
end

View

<%= form_for(@question) do |f| %>
  <%= f.fields_for :surveys do |builder| %>
    <%= builder.label :title %>
    <%= builder.text_field :title, class: 'form-control' %>
  <% end %>
  ...

Upvotes: 1

Views: 353

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

To further Tom Fast's answer, you'll also need to get your associative names sorted properly:

<%= f.fields_for :survey do |builder| %>
    <%= builder.label :title %>
    <%= builder.text_field :title, class: 'form-control' %>
  <% end %>

#app/controllers/questions_controller.rb
class QuestionsController < ApplicationController
   def question_params
      params.require(:question).permit(:content, survey_attributes: [:title])
   end
end

Upvotes: 1

Tom Fast
Tom Fast

Reputation: 1158

It looks like you need to change your question_prams method to specify "survey_attributes".

def question_pramas
  params.require(:question).permit(:content, survey_attributes: [:title])
end

Upvotes: 2

Related Questions