Rails 3 - Controller create action with a many-to-many relationship
I have a many-to-many relationship between two models, Lists and Users.
When a user creates a list, it should automatically add it to the User.lists array. Right now, I have this working but it smell开发者_StackOverflows a bit:
def create
@list = current_user.lists.new(params[:list])
current_user.lists << @list
Is there a way to get this down to one line? Not passing @list into the collection with << but have it there automatically when I build the new list?
Thanks
You just have to do this :
@list = current_user.lists.create(params[:list])
I suggest a slightly different approach to help accommodate your validations.
def create
@list = current_user.lists.new(params[:list])
respond_to do |format|
if (current_user.lists << @list rescue false)
format.html {...}
else
format.html {...}
end
end
end
The big difference is that
current_user.lists << @list
returns the list if it saves successfully (interpreted as true if the result is not false or nil) and exception if it fails, which you rescue and return false. This replaces the traditional
@list.save
which returns true of false, and nil if it does not. Correctly setting up the logic for the if statement inside of the respond_to block.
And it reduces your lines of code by 1.
精彩评论