如何为 rails-settings 插件创建表单 [英] How to create a form for the rails-settings plugin

查看:17
本文介绍了如何为 rails-settings 插件创建表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要一些用户定义设置的 Rails 3 应用程序.我想使用这个 https://github.com/ledermann/rails-settings 插件.我让它在 rails 控制台中工作.但我无法以某种形式工作.我是否使用 fields_for &attr_accessible?如果是这样,我就没有运气了.

I have a Rails 3 App that has needs some user defined settings. I would like to use this https://github.com/ledermann/rails-settings plugin. I have it working in the rails console. But I am having trouble getting working in a form. Do I use fields_for & attr_accessible? If so I am having no luck.

我需要为两个模型添加设置:

I need to add settings for two Models:

例如,特定于用户的设置,

For example, settings that are specific to a User,

user = User.find(123)
user.settings.color = :red
user.settings.color
# => :red

user.settings.all
# => { "color" => :red }

(以上在控制台中对我来说很好用.)

(The above works fine for me in the console.)

但我需要通过标准的网络表单来管理它们.我很想知道其他人是如何处理这个问题的.

but I need to administer them through a standard web form. I'd love to know how others are handling this.

谢谢.

推荐答案

我所做的是将动态 setter/getter 添加到我的 User 类中

What I did is add dynamic setters/getters to my User class as such

class User < ActiveRecord::Base

  has_settings

  def self.settings_attr_accessor(*args)
    args.each do |method_name|
      eval "
        def #{method_name}
          self.settings.send(:#{method_name})
        end
        def #{method_name}=(value)
          self.settings.send(:#{method_name}=, value)
        end
      "
    end
  end

  settings_attr_accessor :color, :currency, :time_zone

end

有了它,您就可以像用户模型的任何其他属性一样使用颜色".添加更多设置也很简单,只需将它们添加到列表中

With that, you can use "color" just like any other attribute of your User model. Also it's very simple to add more settings, just add them to the list

这篇关于如何为 rails-settings 插件创建表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆