除非收藏夹上的current_user工作,否则如何做一个简单的检查?

时间:2016-10-26 18:55:07

标签: ruby-on-rails controller conditional-statements

我正在构建一个应用程序,用户可以将房间添加到收藏夹。它有效,但它也多次重复关系。例如,有人可以多次喜欢同一个房间。因此,我想在控制器中实现检查,遗憾的是我收到此错误:

我该如何使用?

enter image description here

rooms_controller.rb

 before_action :set_room, only: [:show, :favorite]

  def favorite
    type = params[:type]
    if type == "favorite"
      current_user.favorites << @room unless current_user.rooms.exists?(room)
      redirect_to wishlist_path, notice: 'You favorited #{@room.listing_name}'

    elsif type == "unfavorite"
      current_user.favorites.delete(@room)
      redirect_to wishlist_path, notice: 'Unfavorited #{@room.listing_name}'

    else
      # Type missing, nothing happens
      redirect_to wishlist_path, notice: 'Nothing happened.'
    end
  end

  private
    def set_room
      @room = Room.find(params[:id])
    end
end

的routes.rb

  resources :rooms do
    put :favorite, on: :member
  end

show.html.erb

<% if current_user %>
  <%= link_to "favorite",   favorite_room_path(@room, type: "favorite"), method: :put %>
  <%= link_to "unfavorite", favorite_room_path(@room, type: "unfavorite"), method: :put %>
<% end %>

1 个答案:

答案 0 :(得分:1)

如果您的User型号有很多收藏夹,请修正拼写错误:

current_user.favorites << @room unless current_user.favorites.exists?(@room)