orourkedd
orourkedd

Reputation: 6421

Ruby on Rails add model to association

Here are my models:

class Hour < ActiveRecord::Base
  attr_accessible :time, :user
  belongs_to :project
end

class Project < ActiveRecord::Base
  attr_accessible :name
  has_many :hour, :dependent => :destroy
end

I'm trying to do something like this:

hour = Hour.new
#add values to the hour object here
hour.save!
project = Project.find :first
project.hour.add hour #how do I actually do this?
projet.save!

This throws an error. How do I add a model to an association?

I'm coming from a PHP background with Doctrine2. In Doctrine2 I would do something like:

$projects->getHours()->add($hour);

Also, I've read these docs: http://guides.rubyonrails.org/association_basics.html. They seem to cover everything on how to create associations, but I can't find info on how to work with them! Any good docs on how to work with associations?

Upvotes: 0

Views: 1245

Answers (2)

Daniel Rikowski
Daniel Rikowski

Reputation: 72504

You can add it like an array:

project.hours << hour

but often it feels more natural to build the new model directly using the association:

hour = project.hours.build({ your: "...",  attributes: "...", here: "..."})
# Do more stuff with hour
project.save!

(The build method behaves like new, but for technical reasons it must be named build here)

Or in case you want to immedately save the model:

project.hours.create({ your: "...",  attributes: "...", here: "..."})

The Rails documentation has a list of the "magic" methods of associations. Have a look at the has_many Association Reference.

Upvotes: 0

raiis
raiis

Reputation: 382

First, correct name,

has_many :hours

then,

project.hours << hour

4.3.1.2 in http://guides.rubyonrails.org/association_basics.html

Upvotes: 1

Related Questions