使用send()方法时出现未定义的方法错误

时间:2017-09-21 19:26:15

标签: ruby-on-rails ruby

我有一个方法:

.box {
  display: grid;
  grid-template-columns: 1fr 4fr;
  grid-gap: 20px;
  grid-auto-columns: max-content;
  background: #efefea;
  margin: 50px auto;
  padding: 20px;
  box-sizing: border-box;
  .side_panel {
    background:#fff;
    padding:20px;
    box-sizing: border-box;
    .side_panel_box {
      text-align:center;
      border: 1px solid #000;
      margin-bottom:20px;
    }
  }
  .main_panel {
    background:#fff;
    padding:20px;
    box-sizing: border-box;
    display:block;
    grid-auto-columns: max-content;

  }
}

我称之为:

    def complete_sign_in(user, redirect_path, flash_type, message)
      sign_in user
      remember user
      flash[send(flash_type.to_sym)] = message
      redirect_to send(redirect_path.to_s)
    end

由于某种原因, complete_sign_in(@user, 'register_optional_path', 'success', t(:account_activated)) 效果很好,但当我尝试将Flash的类型设置为'register_optional_path'时,它会给我一个错误:

'success'

知道它为什么会这样,以及如何解决它?

2 个答案:

答案 0 :(得分:0)

如果您不使用send,则可以避免此类错误。当您为redirect_pathflash_type传递字符串值时,您可以使用to_sym来创建"创建"重定向的路由,flash[:success]密钥可以作为字符串或符号键访问,因此您可以直接访问它,而无需使用nor .to_s甚至发送。

您可以尝试:

def complete_sign_in(user, redirect_path, flash_type, message)
  sign_in user
  remember user
  flash[flash_type] = message
  redirect_to redirect_path.to_sym
end

我认为你可以调整一下你的方法,比如:

def sign_and_remember(user)
  [method(:sign_in), method(:remember)].each { |method| method.call(user) }
end

def complete_sign_in(options={})
  sign_and_remember(options[:user])
  flash[options[:flash]] = options[:message]
  redirect_to options[:path].to_sym
end

那么你可以通过传递一个包含所需值的哈希来调用它:

options = {
  flash:   'success', 
  message: t(:account_activated),
  path:    'register_optional', 
  user:    @user
}
complete_sign_in(options)

答案 1 :(得分:0)

问题是没有名为success的方法。但无论如何你必须传递一个字符串或符号。

像这样改写:

def complete_sign_in(user, redirect_path, flash_type, message)
  sign_in user
  remember user
  flash[flash_type.to_sym] = message
  redirect_to send(redirect_path.to_s)
end

我还建议您重写redirect_path变量并直接发送方法。

像这样:

def complete_sign_in(user, redirect_path, flash_type, message)
  sign_in user
  remember user
  flash[flash_type.to_sym] = message
  redirect_to redirect_path
end

现在你可以这样称呼它:

complete_sign_in(@user, register_optional_path, 'success', t(:account_activated))