【问题标题】:Rails Change record valuesRails 更改记录值
【发布时间】:2013-07-31 07:38:48
【问题描述】:

我在 postgresql 中有一条用户状态记录,它是布尔值,其属性是“true”和“false”。我想将“true”显示为“active”,将“false”显示为“inactive”。如何使用查询或任何要添加到模型中的东西来做到这一点。

控制器:

     def index
     @users = User.reorder("id ASC").page(params[:page]).per_page(10)
     @count = 0
     end 

型号:

    class User < ActiveRecord::Base
    has_many :orders
    has_many :order_statuses

     attr_accessible :first_name, :last_name, :email, :password,
  :password_confirmation, :code

     validates :first_name, presence: true
     validates :last_name, presence: true
     VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
      validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },          uniqueness: { case_sensitive: false }
     validates :password, length: { minimum: 6}

    has_secure_password
    before_save { self.email = email.downcase }
     before_create :create_remember_token

    def User.new_remember_token
    SecureRandom.urlsafe_base64
    end

    def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
    end

     private

     def create_remember_token
     self.remember_token = User.encrypt(User.new_remember_token)
      end
        end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 attributes ruby-on-rails-3.2 records


    【解决方案1】:

    在你的模型中添加这个方法,当你调用@user.status时,它会显示'Active'或'Inactive'。

    def status
      self.status?  ?  "Active" : "Inactive"
    end
    

    希望,它会有所帮助。谢谢

    【讨论】:

    • 上面的代码给了我无法识别的错误,所以我修改了一下:def User.status self.status ? “活动”:“非活动”结束问题是它仍然没有将值更改为活动。感谢您的帮助
    • 您将其定义为类方法,您不需要这样做。请在此处粘贴您的错误。
    • 好了解决了 我直接把函数写到索引页里了。再次感谢。
    • 索引页?你的意思是索引视图。永远不要在视图中编写函数。
    【解决方案2】:

    如果我对您的理解正确,您希望向您的用户显示“活跃”而不是真和“不活跃”而不是假。

    你可以在你所有的视图中做这样的事情:

    @user.status? ? 'active' : 'inactive'
    

    或者,如果你在很多地方都需要这个,你可以写一个助手:

    module UserHelper
      def status_text(user)
        @user.status? ? 'active' : 'inactive'
      end
    end
    
    # and call it from your views like this:
    
    <%= status_text(@user) %>
    

    或者,如果您只需要将此功能与用户及其活动方法结合使用,则可以将其放入模型方法中(根据 Rails Guy 的建议)

    最后,如果您有一个多语言页面,您可以使用 I18n 为您翻译字符串:

    # en.yml
    en:
      status:
        true: 'active'
        false: 'inactive'
    
    # user_helper.rb
    def status_text(user)
      I18n.t("statys.#{user.status.to_s}")
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      相关资源
      最近更新 更多