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

为君一笑 提交于 2019-12-11 23:25:51

问题


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_entity }
   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 :)


回答1:


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])



回答2:


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


来源:https://stackoverflow.com/questions/6235346/rails-3-build-not-saving-to-database-railscast-196

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!