【问题标题】:Rails 3 -- Build not saving to database (Railscast 196)Rails 3 -- 构建不保存到数据库 (Railscast 196)
【发布时间】:2011-06-04 07:09:12
【问题描述】:

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

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

任何帮助表示赞赏:)

【问题讨论】:

    标签: ruby-on-rails-3 activerecord nested-attributes railscasts


    【解决方案1】:

    假设:

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

    尝试改变:

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

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

    【讨论】:

    • 虽然这可以将外键正确设置为表单表的 app_id,但问题仍未保存。
    【解决方案2】:

    好的,想通了。原来我应该多看看我的控制台。尝试将问题插入数据库时​​挂起的错误是“警告:无法批量分配受保护的属性: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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多