rails:如何在创建时存储model1和model2的值?

时间:2013-05-31 23:13:50

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

创建具有匹配项的学生都是模型,我想在Match中存储来自Student的值。如何处理这个?

我尝试了委托,但是抛出匹配为空的错误,任何想法?谢谢!

用户模型:

class Student < ActiveRecord::Base

  attr_accessible :name, :level

  has_one :match
  before_create :setup_match

  def setup_match
    self.create_match # create the match that belongs to this student
  end


end

匹配模式:

class Match < ActiveRecord::Base

  belongs_to :student
  attr_accessible :initiated, :level

  before_save :default_values

  def default_values
    # HERE is the problem
    # Need to store student.name and student.level here, how?
    self.initiated = student.name
    self.level = student.level
  end


end

1 个答案:

答案 0 :(得分:1)

您应该在学生中移动匹配的设置值..这样的事情(未经测试):

class Student < AR::Base
  has_one :match
  accepts_nested_attributes_for :match

  before_create :setup_match

  def setup_match
    build_match(:initiated => name, :level => level)
  end
end