Rails:可以将参数传递给after_create方法吗? [英] Rails: Can you pass arguments to the after_create method?

查看:80
本文介绍了Rails:可以将参数传递给after_create方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,只有具有管理员角色的用户才能创建新用户。在新用户表单中,我为可能分配给新用户的每个可用角色都有一个选择框。

In my application, only users with the administrator role may create new users. In the new user form, I have a select box for each of the available roles that may be assigned to new users.

我希望使用after_create回调方法来将角色分配给用户。如何在after_create方法中访问选择框的选定值?

I am hoping to use the after_create callback method to assign the role to the user. How can I access the selected value of the select box in the after_create method?

  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        flash[:notice] = 'User creation successful.'
        format.html { redirect_to @user }
      else
        format.html { render :action => 'new' }
      end
    end
  end

我有以下用户模型:

  after_create :assign_roles

  def assign_roles
    self.has_role! 'owner', self
    # self.has_role! params[:role]
  end

我收到一个错误,因为模型不知道

I receive an error because the model doesn't know what role is.

推荐答案

您可以使用 attr_accessor 创建虚拟角色属性并将其设置为创建操作的一部分。

You could use attr_accessor to create a virtual attribute and set that attribute as part of your create action.

这篇关于Rails:可以将参数传递给after_create方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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