简体   繁体   English

在无法在Rails中使用的方法中将属性名称作为参数传递

[英]Passing an attribute name as an argument in a method not working in Rails

I'm trying to define a method in a model to simplify things I'm doing in my controller as below: 我正在尝试在模型中定义一个方法,以简化我在控制器中所做的事情,如下所示:

models/game.rb 型号/game.rb

def build_array_for(words)
  words.downcase.split(",")
end

I'm calling the method in the controller as below 我正在如下调用控制器中的方法

games_controller.rb games_controller.rb

@wordsArray = @game.build_array_for(red_words)

Note that 'red_words' is an attribute of instances of Game which value is supposed to be a string 请注意,“ red_words”是Game实例的属性,该实例的值应为字符串

When I call the method I get: 当我调用该方法时,我得到:

undefined local variable or method `red_words' for GamesController 未定义的局部变量或GamesController的方法“ red_words”

If I build the method as: 如果我将方法构建为:

def build_array
  red_words.downcase.split(",")
end

it works but since I'm using it with other attributes for the same purpose it wouldn't make sense. 它可以工作,但是由于我出于同一个目的将其与其他属性一起使用,因此没有任何意义。

What am I missing here, could it be that the argument is passed as a string and for some reason the name of the attribute is not recognised? 我在这里缺少什么,这可能是因为参数以字符串形式传递并且由于某种原因无法识别属性名称?

If you need build array for existed column then you can try this: 如果您需要为已存在的列构建数组,则可以尝试以下操作:

def build_array_for(column)
  self[column].downcase.split(",")
end

If you want build array for any instance variable when: 如果要在以下情况下为任何实例变量构建数组:

def build_array_for(name)
  self.send(name).downcase.split(",")
end

Use symbol or string for a parameter: 使用符号或字符串作为参数:

@wordsArray = @game.build_array_for(:red_words)

Change the method to 将方法更改为

def build_array_for(words)
  words.downcase.split(",")
end

When you are using self rails will try to find an attribute words or instance method words for Game object 当您使用self将尝试找到Game对象的属性words或实例方法words

EDIT 编辑

Make this changes accordingly 进行相应的更改

games_controller.rb games_controller.rb

@wordsArray = @game.build_array_for(red_words)

models/game.rb 型号/game.rb

def build_array(red_words)
  red_words.downcase.split(",")
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM