Topic: Model Methods

Hi I have a question regarding creating Methods for Models.
Lets say I have a model User and House so what is the proper method for creating methods?
In the User Model I can use
#user.rb
def add_home
self.build_home(:furniture=>1)
self.save
end

or should I put the def initialize in the Home Model then call it
However I can't call call it from user

Can anyone help me adopt the correct way of doing things by give me an example?
I want to use as much of the rails method without creating new unnessary ones.

using rails console it will show argument errors, looks like I have to create my own methods to call it.

Last edited by limgw (2012-06-15 02:01:00)

Re: Model Methods

A lot of things depend on the relations between your models and most ActiveRecord methods Rails has already created for you. See Rails guides and Rails API Documentation for more details.

Re: Model Methods

If you want to improve just a method, I can advice to use create method:
def add_home
  self.create_home(:furniture=>1)
end
But I don't understand for what reasons you need this method with constant attribute. If that method with constant is really needed then set default = to furniture.
If you use it for user creation, then it would be better to use user = User.create(params[:user]) with dependent structures.
Thus, please provide more data to get full response.

Re: Model Methods

you should try adding this line to your migration
:forniture, default => 1

and if you want to create it everytime a user its created you should do this on the user model

before_create :add_home

def add_home
  self.create_home
end

Last edited by jtomasrl (2012-06-20 13:36:33)