开发者

Rails 3 - Controller create action with a many-to-many relationship

开发者 https://www.devze.com 2023-03-31 19:00 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消