简体   繁体   English

Rails模型中不必要的自定义方法

[英]Custom methods unacessible in Rails Model

When I try to: 当我尝试:

class Construction < ActiveRecord::Base
  def columns
    ["a", "b"]
  end   
  store :dados, accessors: columns
end

I get: 我得到:

undefined local variable or method `columns' for #<Class:0x007f891037dac0>

So, how should i do this? 那么,我该怎么做呢?

PS: I have tried putting 'self.' PS:我已经尝试过“自我”。 before columns and it didn't work. 在专栏之前,它没有用。

EDIT — More info about the problem: 编辑—有关该问题的更多信息:

I have set a series of Serialized Hash data stored on the column "dados". 我已经设置了一系列存储在“ dados”列上的序列化哈希数据。 The method store does that and set attribute acessors. 方法存储将执行此操作并设置属性acessors。 I have erased other parts of this code that are not really inherent to the problem, but basically, i need to inform the accesors attribute through a method instead of declaring directly there. 我已经删除了该代码中并非真正属于该问题的其他部分,但基本上,我需要通过一种方法来通知accesors属性,而不是直接在其中声明。 The reason is because i'll reuse the method that generate the columns. 原因是因为我将重用生成列的方法。

I wont be using the method in the instance variables, but instead inside the model itself. 我不会在实例变量中使用该方法,而是在模型本身内部使用。 its for code reusing 它用于代码重用

when you create a method on a model, every instance of that model has its methods, for example if you do this: 在模型上创建方法时,该模型的每个实例都有其方法,例如,如果执行以下操作:

In controller: 在控制器中:

@construction=Construction.first

@construction.columns // will return that array;

can you give me more info on what you need to be done so i can help you better 能给我更多有关您需要做的事情的信息,以便我可以更好地帮助您

mmm im still having trouble understanding the issue but maybe you should do an after create method, something like this: mmm im仍然无法理解问题,但也许您应该执行after after方法,如下所示:

class Construction < ActiveRecord::Base
  after_create :something

  def columns
    ["a", "b"]
  end   

  private
  def something
      store :dados, accessors: self.columns
  end
end

Ok. 好。 I solved it adding self. 我解决了添加自我。 before, changed the columns to a different keyword cause its a rails method and things only worked after restarting the server. 之前,将列更改为其他关键字会导致其使用rails方法,并且只有在重新启动服务器后才能正常工作。 Thanks everyone! 感谢大家!

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

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