在 Rails 中,如何在提交表单时强制从字符串到对象进行对话?

In Rails, how can I force a converstion from a String to an object when my form is submitted?

我正在使用 Rails 4.2.4。我有一个 table“my_objects”,其中有一列“address_id”,它是返回我的“地址”table 的外键。所以在我的 my_object.rb 模型中,我必须创建一个方法来同时保存对象和地址

  belongs_to :address, :autosave => true, dependent: :destroy
  def save_with_address
    transaction do
      if !self.address.nil?
        address = Address.new(self.address)
        address.my_object = self
        address.save
        self.address = address
      end

      # Save the object
      save
    end
  end

作为参考,我的地址对象(在数据库中有一个 state_id 列 dn country_id 列)的结构如下…

class Address < ActiveRecord::Base
  belongs_to :state
  belongs_to :country
  has_one :my_object
end

但是,当我提交表单时,包含以下数据

  Parameters: {"utf8"=>"✓", "my_object"=>{"id"=>"", "name"=>"Dave20", "day"=>"07/06/2016", "distance"=>"10", "distance_unit_id"=>"5", "hour"=>"00", "minute"=>"04", "second"=>"05", "address"=>{"city"=>"baltimore", "state"=>"3555"}, "my_object_times_attributes"=>{"0"=>{"overall_rank"=>"", "age_group_rank"=>"", "gender_rank"=>"", "time_in_ms"=>"245000"}}}, "commit"=>"Save"}   

这一行,“address = Address.new(self.address)”失败并出现错误,“ActiveRecord::AssociationTypeMismatch (State(#70161141072220) expected, got String(#70161059455060)) :”。显然 Rails 没有将我的状态 ID 字符串转换为对象。我怎样才能做到这一点?

您的 Address 模型依赖于另外两个模型 Statecountry,因此当您尝试通过传递 [=14] 为 Address 创建新对象时=] 它引发了错误。

要解决此问题,您必须通过为 statecountry 通过传递值创建新对象并将此对象传递给 Address.new 来更改代码,现在 statecountry 作为 string 传递,所以显然它不会起作用

希望这会有所帮助。

使用accepts_nested_attributes_for method. For more detailed explanation see