Ruby on Rails: defining a method with parameters

I want to define a method that allows me to pass parameters; sort of:

@user.tasks(:completed => true)

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

User.rb Model

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

How do I correctly define a method to allow me to use @ user.tasks (: completed => true)?

+3
source share
5 answers

This is basically how I do it:

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

There are several ways to pass parameters, but you definitely want to pass a hash with a default value (so that you can call the method without parameters).

In your case, indicate what you want to do:

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

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

I have not tested, but it should be fine

2: , EmFi, . . @thing.tasks.find(:all, :conditions => {blah})

+6

has_many :tasks? , , . Rails , , :

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

:

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

, 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
+5

? , . ActiveRecord.

ActiveRecord:: Base # all (options), Task.find(: all, options)

:

class User < ActiveRecord::Base
  has_many :tasks
end

@user.tasks.all(:conditions => {:completed => true})
+2

:

[: ]

+1

Activerecord provides a method called with_scope, so to pass any additional conditions

@user.tasks(:completed => true)

you can define the task method as

def tasks(options={})
  with_scope :find => options
    User.all :order => 'id desc'
  end
end

and this will combine any hash passed as a parameter parameter with the actual find

The only caveat is that you need to change your method a bit.

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

or something like

@user.tasks(:select => 'username')

But if there is a connection between the user model and the tasks, I would do what Jordan has in its message

0
source

Source: https://habr.com/ru/post/1725170/


All Articles