Beginner question on active record relationships


#1

say I have the following:

user table

- id

- username

- password

class User < ActiveRecord::Base
has_many :items
end

item table

- id

- user_id

- name

class Item < ActiveRecord::Base
belongs_to :user
end

What is the correct way for creating a new item instance with
relationships in place (assuming the current user is available in the
current_user instance)? Do you have to manually associate the models
like the following?

def create_item
@item = Item.new(params[:name])
@item.user_id = current_user
current_user.items << @item

@item.save
end


#2

Ryan M. wrote:

What is the correct way for creating a new item instance with
relationships in place (assuming the current user is available in the
current_user instance)? Do you have to manually associate the models
like the following?

def create_item
@item = Item.new(params[:name])
@item.user_id = current_user
current_user.items << @item

@item.save
end

This will do everything your create_item method does:

user.items.create(:name => params[:name])

There is also a build() method that makes a new item but doesn’t save
it.

Look at the docs for the has_many association for descriptions of these
methods.
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000471

–josh
http://blog.hasmanythrough.com