如何在Rails模型的回调中访问参数? [英] How to access params in the callback of a Rails model?

查看:104
本文介绍了如何在Rails模型的回调中访问参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型的回调,该模型需要根据表单中输入的另一个字段创建一个依赖对象。但是 params 在回调方法中未定义。还有另一种访问方式吗?从表单传递回调方法参数的正确方法是什么?

I have a callback of a model that needs to create a dependent object based on another field entered in the form. But params is undefined in the callback method. Is there another way to access it? What's the proper way to pass a callback method parameters from a form?

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :enrollments

  after_create :create_enrollment_log
  private
  def create_enrollment_log
    enrollments.create!(status: 'signed up', started: params[:sign_up_date])
  end
end


推荐答案

在模型中无法访问参数,即使您将它们作为参数传递,也将被视为不正确的做法,并且也很危险。

您可以做的就是创建虚拟属性并将其在模型中使用。

What you can do is to create virtual attribute and use it in your model.

class User < ActiveRecord::Base
 attr_accessible :name, :sign_up_date
 has_many :enrollments

 after_create :create_enrollment_log
 private
 def create_enrollment_log
   enrollments.create!(status: 'signed up', started: sign_up_date)
 end
end

其中sign_up_date是您的虚拟属性

Where sign_up_date is your virtual attribute

这篇关于如何在Rails模型的回调中访问参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆