在强参数中添加参数

时间:2015-04-23 16:35:20

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

让我说我有这样的参数:

def boat_params
   params
      .require(:boat)
      .permit(:message
              :alarm_en,
              :alarm_es,
              :alarm_sv)
end

我尝试的基本上是缩短此代码,其中包含:

def boat_params
   params
      .require(:boat)
      .permit(:message).merge(alarm_params)
end

但对于alarm_params我在尝试时会出错:

def alarm_params
    params = {}
    ["en","es","sv"].each do |lang|
       params << "alarm_#{lang}" 
    end
    return params
end

引发错误的原因是什么:

undefined method `<<' for {}:Hash

for:params << "alarm_#{lang}"

接下来我尝试使用数组:

def alarm_params
    params = []
    ["en","es","sv"].each do |lang|
       params << "alarm_#{lang}" 
    end
    return params
end

引发错误的原因是什么:

 undefined method `to_hash' 

.merge(alarm_params)

我错了什么?谢谢!

2 个答案:

答案 0 :(得分:1)

您在#include <stdio.h> #include <string.h> #include <stdbool.h> bool endsWith(const char* haystack, const char* needle) { bool rv = false; if (haystack && needle) { size_t needle_size = strlen(needle); const char* act = haystack; while (NULL != (act = strstr(act, needle))) { if (*(act + needle_size) == '\0') { rv = true; break; } act += needle_size; } } return rv; } int main (int argc, char * argv[]) { char *a = "file1.gz"; char *b = "1.gz"; char *c = NULL; char *d = "1.gzabc"; char *e = "1.gzabc1.gz"; printf("endsWith:\n"); printf("%s %s = %d\n",a,b,endsWith(a,b)); printf("%s NULL = %d\n",a,endsWith(a,c)); printf("%s %s = %d\n",d,b,endsWith(d,b)); printf("%s %s = %d\n",e,b,endsWith(e,b)); return 0; } 的结果上调用merge,返回permit,而不是通用哈希。

由于ActionController::Parameters采用数组,您实际上可以执行以下操作:

permit

如果您想使用元编程来提取语言列表并为每个语言创建允许的参数,正如您在def alarm_params %w{ alarm_en alarm_es alarm_sv } end def boat_params params.require(:boat).permit(:message, *alarm_params) end 中所做的那样,您可以更轻松地执行以下操作:

alarm_params

无需def languages # possibly use a more global config var, or ENV # e.g. ENV['SUPPORTED_LANGUAGES'] %w{ en es sv } end def alarm_params languages.map { |lang| "alarm_#{lang}" } end 或明确的each

答案 1 :(得分:1)

permit的参数是一个数组,而不是一个哈希。您可以尝试使用splat运算符*

def boat_params
   params
      .require(:boat)
      .permit(:message, *alarm_params)
end