0

我正在关注 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

以下是发送到我的 create 方法的参数:

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

这表明参数正在正确发送......我认为。问题模型只有一个“内容”文本列。

任何帮助表示赞赏:)

4

2 回答 2

0

假设:

  1. 您已正确设置表单,
  2. 您的服务器显示您的数据正在发送到新操作,并且
  3. 您的模型不包含阻止保存的回调,

尝试改变:

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

@form = @app.forms.build(params[:form])
于 2011-06-04T07:25:23.767 回答
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
于 2011-06-05T22:08:41.087 回答