Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Defining a method with options

I'm looking to define a method that lets me pass options; something like:

@user.tasks(:completed => true)

I thought something like this would work in my user model (but it's not):

User.rb model

  def tasks(options)
    tasks.find(:all, options)
  end

How would I define the method correctly to let me use @user.tasks(:completed => true)?

like image 361
sjsc Avatar asked Feb 05 '26 19:02

sjsc


2 Answers

This is basically how I'd do it:

def tasks(options={})
  unless options[:something].blank? 
    # do stuff
  end
end

There are some different ways to pass options, but you definitively want to pass a hash with a default value (so that you can call the method without options).

In your case the following should address what you want to do:

def tasks(options={})
  Task.find(:all, options[:conditions])
end

Edit: and then call it @thing.tasks( {:conditions => "blah"} )

I haven't tested but it should be ok

Edit 2: But like EmFi said it's not optimal to do this. Consider using an association instead. You'll be able to go @thing.tasks.find(:all, :conditions => {blah})

like image 159
marcgg Avatar answered Feb 07 '26 17:02

marcgg


Does User have a has_many :tasks association? That seems to be what you're after here. In that case Rails provides finders for you, which you can access like this:

@user.tasks.find :all, :conditions => { :completed => true }

Or even shorter:

@user.tasks.all :conditions => { :completed => true }

If that's not terse enough and you always want to use a particular condition, try a named scope:

# In your Task model:    
named_scope :completed, :conditions => { :completed => true }

# Then you can just call...
@some_user.tasks.completed # => Only completed Tasks for @some_user
like image 38
Jordan Running Avatar answered Feb 07 '26 18:02

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!