【问题标题】:Rails 3: save method wont workRails 3:保存方法不起作用
【发布时间】:2013-03-17 20:10:21
【问题描述】:

我正在构建我的第一个 Rails 应用程序,到目前为止一切正常,但后来我发现了以下场景:一个演示文稿应该有 N 次迭代。我没有使用 REST。所以,我试图制作一个简单的表单来创建迭代。

这些是模型:

class Presentation < ActiveRecord::Base
  has_many :iterations
end

class Iteration < ActiveRecord::Base
  belongs_to :presentation
  attr_accessible :presentation_id, :description, :delivery_date, :file
  validates :presentation_id, :presence => {:message => 'is required.'}
end

这些是控制器中的操作:

#Shows Form
def add
  @iteration = Iteration.new
  @presentation = Presentation.find(params[:id])
end

#Saves Form
def save
  @iteration = Iteration.new(params[:iteration])
  @iteration.delivery_date = Time.now
  if @iteration.save
    flash[:notice] = "Saved succesfully!"
  else
    flash[:error] = "Changes were not saved."
  end
  redirect_to root_url
end

这些将是 HAML 中的视图:

= form_for @iteration, :url => { :action => "save", :method => "post" }, :html => { :multipart => true }  do |f|

- if @iteration.errors.any?
  There were some errors:
  .notice-text.fg-color-white
    %ul.notice
    - for message in @iteration.errors.full_messages
      %li= message
%br

.field
  = f.label :description, "Description"
  = f.text_area :description, :class=>"form-text-area", :rows=>5
.field
  = f.label :file, "Upload File"
  = f.file_field :file
.field
  = hidden_field_tag :presentation_id, @presentation.id
%br
= f.submit "Save"

问题是,save 方法不会保存,但是 @iteration.errors.count 在视图上的值是 0。 我用然后保存!相反,正如我在另一篇文章中所读到的那样,它会引发以下错误:

验证失败:需要演示。

我不知道我做错了什么。请注意,在视图中,我曾经使用“f.hidden_​​field”而不是“hidden_​​field_tag”,但由于其他原因我更改了它,但在此之前我遇到了同样的错误。

【问题讨论】:

  • 我注意到没有一个属性到达控制器...

标签: ruby-on-rails ruby-on-rails-3 rails-activerecord


【解决方案1】:

你的 HAML,

hidden_field_tag :presentation_id

需要,

f.hidden_field :presentation_id, :value => @presentation.id

【讨论】:

  • 我确实尝试过 f.hidden_​​field 但我仍然遇到同样的错误。
  • 我尝试了您的解决方案,但同样的错误...我发现如果我执行@iteration.presentation = Presentation.find... 之类的操作,那么它确实有效。我的意思是,就像表单传递的对象从未附加到任何演示文稿 =/
【解决方案2】:

查看您可以拥有的模型定义,

  1. 嵌套资源:参考Controller path for nested resource - undefined method `<controller>_path'

  2. 使用虚拟属性:Ryan 对此非常有用的轨道广播 -> http://railscasts.com/episodes/16-virtual-attributes-revised

  3. 将演示文稿ID保存在会话中:(这不是一个干净非常干净的方法)

在您的控制器上,您需要在演示文稿上实例化迭代,以便正确填充演示文稿 ID。

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    相关资源
    最近更新 更多