Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RubyonRails->;元编程-基于has\u many关系创建属性可访问属性的动态数组_Ruby On Rails_Ruby_Ruby On Rails 3_Ruby On Rails 3.1 - Fatal编程技术网

Ruby on rails RubyonRails->;元编程-基于has\u many关系创建属性可访问属性的动态数组

Ruby on rails RubyonRails->;元编程-基于has\u many关系创建属性可访问属性的动态数组,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-3.1,Ruby On Rails,Ruby,Ruby On Rails 3,Ruby On Rails 3.1,Rails 3.1、Ruby 1.9.2 我正在尝试将Railscasts第345集(HSTORE)改编为我正在构建的应用程序——这个问题不是以HSTORE为中心的……因为如果我序列化属性哈希,我也会遇到它 以下是我有一个问题的代码: Class Product < ActiveRecord::Base has_many :properties %w[author rating runtime].each do |key| # *****--> PLEASE SEE BELOW

Rails 3.1、Ruby 1.9.2

我正在尝试将Railscasts第345集(HSTORE)改编为我正在构建的应用程序——这个问题不是以HSTORE为中心的……因为如果我序列化属性哈希,我也会遇到它

以下是我有一个问题的代码:

Class Product < ActiveRecord::Base

has_many :properties

%w[author rating runtime].each do |key| #  *****--> PLEASE SEE BELOW!
  attr_accessible key
  scope "has_#{key}", lambda { |value| where("properties @> (? => ?)", key, value) }

  define_method(key) do
    properties && properties[key]
  end

  define_method("#{key}=") do |value|
    self.properties = (properties || {}).merge(key => value)
  end
end
但这是行不通的!!我在属性关系上得到了一个未定义的方法错误(我假设这是因为模型还没有实例化?),我对编程相当陌生,对元编程一无所知

编辑-我已经尝试将所有这些移到一个after_find钩子中,但这也不起作用(以及其他几十次不成功的尝试)。所以丢失了


非常感谢您的帮助

经过几天的黑客攻击,我想我终于找到了答案

非常感谢任何和所有关于此解决方案“声音”的小齿轮

简言之,我所做的只是将上述代码块(以%符号开头)包装到如下方法中:

def dynamic_accessible_and_setters(*details)
  details.each do |key| # I placed the details variable here instead of the %w[]
    attr_accessible key
    scope "has_#{key}", lambda { |value| where("properties @> (? => ?)", key, value) }

    define_method(key) do
      properties && properties[key]
    end

    define_method("#{key}=") do |value|
      self.properties = (properties || {}).merge(key => value)
    end
  end
end
然后,在控制器中,我只是从类中调用了该方法并分配了属性数组:

def edit
  PRODUCT.dynamic_accessible_and_setters("author", "rating", "runtime")
  ...
end
现在,我已经为类的每个实例动态地构建了getter、setter和attr_可访问、自定义(或者,我认为是这样的?!)


我希望这对别人有帮助!现在来看看多个db写入与序列化和一个写入的性能权衡。

方法属性仅适用于产品实例。是否要完全替换@product.properties的语义?(即,Remouse has_many:properties),或者您希望保留正常语义并以某种方式对其进行补充吗?感谢您的回复-我希望保留正常语义(因为我希望仍然能够查询@product.properties),但要添加到它们中。例如,如果产品1只分配了属性author和rating,我想将runtime属性排除在该实例的可访问属性列表之外。另一方面,如果产品通过连接分配了所有属性,我希望所有属性都可以访问。。。
def edit
  PRODUCT.dynamic_accessible_and_setters("author", "rating", "runtime")
  ...
end