ActiveRecord的最佳方法:如果存在,则删除,否则创建

Nik*_*las 3 ruby activerecord ruby-on-rails

我有此方法可为某个提示创建收藏夹:

def favorite
  @tip = Tip.find(params[:id])
  Favorite.create(user: current_user, tip: @tip)
  redirect_to :action => "show", :id => @tip.id
end
Run Code Online (Sandbox Code Playgroud)

我希望它更像一个拨动开关。因此:如果某个提示的用户收藏夹已经存在,则应删除该收藏夹。如果是用户和提示的新组合,则应使用这些值创建一个新的收藏夹。

最好和最美丽的方法是什么?

Naf*_*fer 6

试试这个,我认为它是最简洁的解决方案:

def favorite
  # Since this is about a favorite object, the main subject here 
  # is that favorite object, so you just need to deal with it
  favorite = Favorite.find_or_initialize_by(user_id: current_user.id, tip_id: params[:id])
  favorite.persisted? ? favorite.destroy : favorite.save
  # I do not know if you should redirect to this tip if 
  # the associated favorite has been deleted 
  redirect_to favorite.tip
end
Run Code Online (Sandbox Code Playgroud)