保存前更新表单的嵌套属性

时间:2014-04-19 05:59:48

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

我有一个map.rb接受详细信息的嵌套属性,它具有embeds_one关系

详细说明有一个规则数组,我希望用户能够输入一个充满规则的textarea,并通过换行符分隔成数组。我尝试了before_create回调n map.rb和detail.rb,但它们没有被正确触发,导致Mongo字段错误。如果你知道如何在这种情况下使用before_create,那就是我尝试过的:

class Map
  include Mongoid::Document
  include Mongoid::Timestamps

  field :uploader, type: String
  field :upload_date, type: Date

  embeds_many :teams
  embeds_one :detail

  accepts_nested_attributes_for :detail, :allow_destroy => true
  accepts_nested_attributes_for :teams, :allow_destroy => true

  before_validation :fix_rules

  def fix_rules
    detail = self.detail
    detail.rules = detail.rules.gsub("\r", "").split("\n")
  end
end

然后尝试将before_validation放入detail.rb

class Detail
  include Mongoid::Document
  field :name, type: String
  field :version, type: String
  field :objective, type: String
  field :proto, type: String, :default => "1.3.3"
  field :rules, type: Array, :default => []

  embeds_many :contributors

  embedded_in :map
  accepts_nested_attributes_for :contributors, :allow_destroy => true
  before_validation :fix_rules

  def fix_rules
    self.rules = self.rules.gsub("\r", "").split("\n")
  end
end

但似乎都没有用,所以我试图在控制器中坚持更新字段,但这不起作用

def create
  @submission = Map.new(map_params)
  details = params[:map][:detail_attributes]
  if details[:rules].kind_of?(String)
    details[:rules] = details[:rules].gsub("\r", "").split("\n")
  end

  if @submission.save
    flash.now[:notice] = 'Thanks for the map submission!'
    redirect_to maps_path
  else
    flash.now[:error] = 'Submission failed, try again?'
    render :new
  end
end

如果你知道一种方法可以修复我的三次尝试中的任何一次,那将是非常棒的,因为我之前会有一个回调方法。

这是操作的控制台输出:

Started POST "/maps" for 127.0.0.1 at 2014-04-19 00:45:20 -0500
Processing by MapsController#create as HTML
  Parameters: {"utf8"=>"✓",     "authenticity_token"=>"L+EkbFCx6WEiLTSxGpAZuqwdrhLlGAtwaHOqFx7+AHc=", "map"=>    {"detail_attributes"=>{"name"=>"", "proto"=>"1.3.3", "version"=>"", "objective"=>"",    "rules"=>"Gi\r\ns\r\ns\r\ns\r\ns\r\ns", "contributors_attributes"=>{"0"=>{"name"=>"",    "contribution"=>"", "_destroy"=>"false"}}}, "teams_attributes"=>{"0"=>{"name"=>"", "color"=>"", "size"=>"", "max_overfill"=>"", "_destroy"=>"false"}}}, "commit"=>"Submit"}
Completed 500 Internal Server Error in 2ms

0 个答案:

没有答案