开发者

Rails 3 -- Build not saving to database (Railscast 196)

I'm following along with railscast 196. I've got two levels of associations. App -> Form -> Question. This is the new action in the form controller.

def new
 @app = App.find(params[:app_id])
 @form = Form.new
 3.times {@form.questions.build }
end

the view is displaying all 3 questions fine and I can submit the form... but nothing is inserted into the database for the questions. Here is my create action

def create
 @app = App.find(params[:app_id])
 @form = @app.forms.create(params[:form])

 respond_to do |format|
   if @form.save
     format.html { redirect_to(:show => session[:current_app], :notice => 'Form was successfully created.') }
     format.xml  { render :xml => @form, :status => :created, :location => @form }
   else
     format.html { render :action => "new" }
     format.xml  { render :xml => @form.errors, :status => :unprocessable_en开发者_运维知识库tity }
   end
 end
end

Here are the params that are sent to my create method:

    {"commit"=>"Create Form",
    "authenticity_token"=>"Zue27vqDL8KuNutzdEKfza3pBz6VyyKqvso19dgi3Iw=",
     "utf8"=>"✓",
     "app_id"=>"3",
     "form"=>{"questions_attributes"=>{"0"=>{"content"=>"question 1 text"},
     "1"=>{"content"=>"question 2 text"},
     "2"=>{"content"=>"question 3 text"}},
     "title"=>"title of form"}}`

This shows that the params are being sent correctly... I think. The question model just has a "content" text column.

Any help appreciated :)


Assuming:

  1. You have your form set up properly,
  2. Your server shows your data is being sent to the new action, and
  3. Your model doesn't contain callbacks that are blocking the save,

try changing:

@form = @app.forms.create(params[:form])

to

@form = @app.forms.build(params[:form])


Ok figured it out. Turns out I should have been looking at my console a little more. The error it was hanging up on when trying to insert questions into the db was "Warning: can't mass assign protected attributes :questions_attributes". Adding this into the accessible attributes did the trick.

class Form < ActiveRecord::Base
    belongs_to :app
    has_many :questions, :dependent => :destroy
    accepts_nested_attributes_for :questions
    attr_accessible :title, :questions_attributes
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜