在循环中添加 Rails ActiveRecord 关联
我想通过关联为数组中的每个符号添加一个 has_many 到 activerecord 模型类。例如,
PeopleOrganisation::ROLES.each do |role|
has_many role.to_s.pluralize.to_sym, :through => :people_organisations, :source => :person,
:conditions => "people_organisations.role = '#{role.to_s}'" do
def << (object)
PeopleOrganisation.send(:with_scope, :create => {:role => **role**}) { self.concat object }
end
end
end
除了 def 方法中对角色变量的引用之外,一切正常。这是因为 def 方法不是闭包。有办法实现我想要的吗?
I want to add a has_many through association to a activerecord model class for each symbol in an array. for example
PeopleOrganisation::ROLES.each do |role|
has_many role.to_s.pluralize.to_sym, :through => :people_organisations, :source => :person,
:conditions => "people_organisations.role = '#{role.to_s}'" do
def << (object)
PeopleOrganisation.send(:with_scope, :create => {:role => **role**}) { self.concat object }
end
end
end
everything works fine except for the reference to the role variable inside the method def. This is because the method def is not a closure. Is there a way of achieving what I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
Try this:
您可以尝试使用
define_method
方法,而不是使用def
定义方法:Instead of defining method using
def
you can trydefine_method
method: