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
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.
–josh
http://blog.hasmanythrough.com