我正试图解决一个奇怪的问题。 我正在使用模块扩展ActiveRecord。
module StringyAssociationIds
def stringy_ids(association)
define_method("stringy_#{association}_ids=") do |comma_seperated_ids|
self.send("#{association}_ids=", comma_seperated_ids.to_s.split(","))
end
define_method("stringy_#{association}_ids") do
send("#{association}_ids").join(",")
end
end
end
ActiveRecord::Base.extend(StringyAssociationIds)
我有一个班级“门”,我有一个协会。
class Gate < ActiveRecord::Base
include Productable
stringy_ids :product
end
使用连接表定义关联:
module Productable
extend ActiveSupport::Concern
included do
has_many :productable_products, as: :productable
has_many :products, through: :productable_products
end
end
当我尝试创建一个新的Gate时,我有一个错误:
undefined method `stringy_ids' for #<Class:0x007f91e12bb7e8>
我的错在哪里?
编辑:我还尝试在lib目录中添加扩展(由application.rb自动加载)
module ActiveRecordExtension
extend ActiveSupport::Concern
def stringy_ids(association)
define_method("stringy_#{association}_ids=") do |comma_seperated_ids|
self.send("#{association}_ids=", comma_seperated_ids.to_s.split(","))
end
define_method("stringy_#{association}_ids") do
send("#{association}_ids").join(",")
end
end
end
# include the extension
ActiveRecord::Base.send(:include, ActiveRecordExtension)
我也在控制台中尝试:
ActiveRecordExtension.instance_methods
=> [:stringy_ids]
所以我的扩展程序已加载...
答案 0 :(得分:3)
您的课程方法 if(buttonOne)
{
//set the image view 1 image
}
if(buttonTwo)
{
//set the image view 2 image
} if(buttonThree)
{
//set the image view 3 image
} if(buttonFour)
{
//set the image view 4 image
}
在stringy_ids
上定义,而不是ActiveRecord::Base
。与实例方法不同,类方法不会被继承,因为Gate
的单例类不是Gate
的单例类的子类。
答案 1 :(得分:0)
StringyAssociationIds
未延期
实际上,ActiveRecord::Base.extend(StringyAssociationIds)
没有运行。在config/initializer