views:

21

answers:

2

Taking this article as a starting point:

Rails Way Blog - Association Proxies

and looking specifically at

def create
  @todo_list = current_user.todo_lists.build params[:todo_list]
  if @todo_list.save
    redirect_to todo_list_url(@todo_list)
  else
    render :action=>'new'
  end
end

This is a way of making sure you assign ownership to the user

BUT supposing the ToDo list was a many-many relationship associated in a has_many through i.e.

def User < AR:Base
  has_many :user_todos
  has_many :todo_lists, :through => :user_todos
end

At this point...

@todo_list = current_user.todo_lists.build params[:todo_list]

still works but only the todo_list is saved and not the join. How can I get the joy of association proxies without having lots of nested if/else should the join or Todo instance not validate when saved.

I was thinking of something along the lines of...

@todo_list = cu.user_todos.build.build_to_do(params[:todo_list])

but as I mentioned above the user_todos don't get saved.

Your help is greatly appreciated!

Kevin.

A: 

Try doing something along the lines of:

current_user.todo_lists << TodoList.new(params[:todo_list])
vegetables
Thanks Matt. I've never really understood the difference between build and what you've done here to be honest. Not sure if this is a good answer or not!? :) but thanks for making me look at it differently.
Kevin Monk
Thinking about it some more - I guess build allows you to assign the new ToDoList instance to a variable on a single line. without having to do:@todo_list = ToDoList.new(params[:todo_list])current_user.todo_lists << @todo_list
Kevin Monk
A: 

I got it working...

At first I had:

@todo_list = @user.todo_lists.build params[:todo_list]
@todo_list.save!

This works when TodoList simply belongs_to User but not when it's a many-to-many relationship. When I changed the relationship I had to do...

@todo_list = @user.todo_lists.build params[:todo_list]
@user.save!

This saved the @user, the join and the @todo_list.

Obvious I suppose but then I wonder if the original example should also

current_user.save!

instead of

@todo_list.save!

I thought the idea behind build was that it validates and saves the associations when you save the parent so does the example at Rails Way miss the point? or more likely am I?

Kevin Monk