0

我跟随railscast 196.我有两个级别的关联。应用程序 - >表单 - >问题。这是表单控制器中的新操作。Rails 3 - 构建不保存到数据库(Railscast 196)

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

视图中显示所有3个问题很好,我可以提交表单...但没有被插入到数据库中的问题。这是我创造的动作

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 

这里是发送到我的创建方法PARAMS:

{"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"}}` 

这表明PARAMS都被正确发送......我想。问题模型只有一个“内容”文本列。

任何帮助表示赞赏:)

回答

0

好了它。原来,我应该一直在看我的控制台。当试图将问题插入数据库时​​,挂起的错误是“警告:无法批量分配受保护的属性:questions_attributes”。将这添加到可访问的属性中就有诀窍。

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

假设:

  1. 你有你的形式设置不当,
  2. 你的服务器显示的数据被发送到新的动作,并
  3. 你模型不包含阻止保存的回调,

尝试更改:

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

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

虽然这适用于将外键正确设置到app_id窗体表格中,但问题仍然未保存。 – Msencenb 2011-06-05 21:05:07