【问题标题】:rails: how to store values from model1 inside model2 upon creation?rails:如何在创建时将 model1 中的值存储在 model2 中?
【发布时间】:2013-05-31 23:13:49
【问题描述】:

使用匹配创建学生都是模型,我想将学生的值存储在匹配中。应该如何解决这个问题?

我尝试了委托,但抛出了匹配为空的错误,有什么想法吗?谢谢!

用户模型:

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

【问题讨论】:

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


    【解决方案1】:

    您应该在 Student 中移动 Match 的设置值.. 像这样(未测试):

    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
    

    【讨论】:

    • 非常感谢在尝试了一些变化后我最终得到了可行的解决方案
    猜你喜欢
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多