1

In my Rails 4 application I have a (non-ActiveRecord) model containing the plans that a user can subscribe to:

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.

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.

1
  • 2
    what filters are you trying to apply. Please supply output examples. by the way I think the methods you want are Enumerable#find_all or Enumerable#select and then in the block use standard Hash access methods Commented Jan 15, 2015 at 18:40

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I think I am pretty close to what I need now. The only problem is that I get errors like undefined method 'name' for #<Array:0x00000101a47308> when trying to use these methods on the front end like I used to with ActiveRecord. Will I have to convert them to an ActiveRecord::Relation or something similar maybe?
well there is no name method there. The way your are doing it you are pretty much going to have to rewrite functionality that exists in active record.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.