Forum: Ruby on Rails beginner question on active record relationships

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ryan M. (Guest)
on 2006-03-16 20:52
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
Josh S. (Guest)
on 2006-03-16 23:01
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/As...

--josh
http://blog.hasmanythrough.com
This topic is locked and can not be replied to.