How to create a method such as: @user.travels.register(.)

Hi,

In order to trim my controllers down and keep the code in the correct
place, I am trying to refactor:

@user.travels.create(:name => …, :date => …, :ip => request…,
etc)

to:

@user.travels.register(params, request)

So my questions are:

  1. is create() an instance method of Travel? I have doubts, since
    Travel.create is a class method.

  2. how to write my register method() so that it behaves like create()?

Thanks for your help.

Thank you Frederick. I now know where and what to look for.

On Mar 2, 2:59pm, Fernando P. [email protected] wrote:

@user.travels.register(params, request)

So my questions are:

  1. is create() an instance method of Travel? I have doubts, since
    Travel.create is a class method.

it’s not. It’s a method on the association proxy

  1. how to write my register method() so that it behaves like create()?

There are 2 possible ways to go.

The first is the associations are scopes: if you have a class method
on Travel called foo, then user.travels.foo calls the foo class method
but active record calls will be scoped to the travels for that user.

The second is association extensions. If you do

has_many :foos do
def bar
end
end

then you will be able to call user.foos.bar. There’s some more info
here:

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs