在轨道中保存多态模型

时间:2015-02-13 20:38:25

标签: ruby-on-rails polymorphic-associations

我有一个多态模型;结果,belongs_to result_table, polymorphic: true与其他两个模型一起使用;团队和运动,通过一对一的关系及其工作。由于一对一的关系,我有一个回调函数after_create :build_result_table,我在设置和保存数据库结果表中的result_table_idresult_table_type时使用它。我遇到的问题是输入保存在result_table_type,它的VARCHAR,但似乎是将输入保存为整数

def build_result_table
  Result.create(result_table_id: self.id, result_table_type: self)
end

我认为问题可能在于result_table_type: self,但我尝试result_table_type: self.class.name来保存类的名称,但它引发了错误。关于在result_table_type列中保存唯一值的任何建议..


修改

我正在添加所涉及的模型,虽然我已经按照@Mohammad在评论中手动完成了保存,但也会感激,如果我可以显示我如何可以请求rails自动保存值。

APP /型号/ SPORT.RB

class Sport < ActiveRecord::Base
 attr_accessible :sport_name, :sport_id, :result_attributes, :result_table_id
 has_one :result, as: :result_table

 after_create :build_result_table
 accepts_nested_attributes_for :result

 def build_result_table
    Result.create(result_table_id: self.id, result_table_type: self.class.name)
 end

end

APP /型号/ TEAM.RB

class Team < ActiveRecord::Base
 has_one :result, as: :result_table

 attr_accessible :teamname, :color, :result_attributes

 after_create :build_result_table

  accepts_nested_attributes_for :result

 def build_result_table
   Result.create(result_table_id: self.id, result_table_type: self.class.name)
 end

end

APP /型号/ RESULT.RB

 class Result < ActiveRecord::Base
  attr_accessible :sport_id,:team_id, :result_table_id, :result_table_type
  belongs_to :result_table, polymorphic: true
end

1 个答案:

答案 0 :(得分:0)

# Either one of these
Result.create(result_table: self)
Result.create(result_table_id: self.id, result_table_type: self.class.to_s)
相关问题