简体   繁体   English

如何在Ruby on Rails中过滤嵌套哈希?

[英]How to filter nested hash in Ruby on Rails?

In my Rails 4 application I have a (non-ActiveRecord) model containing the plans that a user can subscribe to: 在我的Rails 4应用程序中,我有一个(非ActiveRecord)模型,其中包含用户可以订阅的plans

class Plan

  PLANS = {
    'free'            => { :name => "Free",     :amount => 0,     :interval => '',   :maximum => FREE_MAXIMUM },
    'basic_monthly'   => { :name => "Basic",    :amount => 500,   :interval => 'month', :maximum => BASIC_MAXIMUM },
    'basic_yearly'    => { :name => "Basic",    :amount => 5000,  :interval => 'year',  :maximum => BASIC_MAXIMUM },
    'premium_monthy'  => { :name => "Premium",  :amount => 1000,  :interval => 'month', :maximum => PREMIUM_MAXIMUM },
    'premium_yearly'  => { :name => "Premium",  :amount => 10000, :interval => 'year',  :maximum => PREMIUM_MAXIMUM }
  }

  def self.all
    ...
  end

  def self.all_payable
    ...
  end

  def self.by_interval(interval)
    ...
  end

end

I have worked with ActiveRecord a lot but in this case I don't know how to filter the hash values so I can render them out to the front end. 我已经与ActiveRecord进行了大量合作,但是在这种情况下,我不知道如何过滤哈希值,因此无法将其呈现到前端。

class PagesController < ApplicationController

  def pricing
    @plans = Plan.all
  end

end

How can this be done? 如何才能做到这一点?

Maybe my approach is entirely wrong and it's easier to store the plans in an array? 也许我的方法是完全错误的,并且将计划存储在数组中更容易?

Thanks for any help. 谢谢你的帮助。

An array or a hash would work for this. 数组或哈希将对此起作用。 If I understand you correctly, your methods should look something like this. 如果我正确理解您的方法,则您的方法应类似于以下内容。

def self.all
  # returns the entire PLANS hash
  PLANS
end

def self.all_payable
  # only return hash elements that are not free
  PLANS.find_all { |k,v| v[:name] != 'Free' }
end

def self.by_interval(interval)
  # return all elements where the :interval matches interval
  PLANS.find_all { |k,v| v[:interval] == interval }
end

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM