我已经使用has_many:through关联实现了一个添加到收藏夹功能。用户现在可以在房间show.html.erb视图中收藏或不喜欢房间。在不同的控制器和视图上,我想显示登录用户的所有喜欢的房间。
我希望用户能够删除每个喜欢的房间。展示所有房间是没有问题的,不幸的是我不能用不受欢迎的按钮来完成这项工作。
我该如何使用?
rooms_controller.rb
before_action :set_room, only: [:show, :favorite]
...
def favorite
type = params[:type]
if type == "favorite"
current_user.favorites << @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
static_pages_controller.rb
def wishlist
end
wishlist.html.erb
<div>
<% current_user.favorites.each do |room| %>
<%= room.listing_name %>
<%= link_to "unfavorite", favorite_room_path(@room, type: "unfavorite"), method: :put %>
<% end %>
</div>
的routes.rb
Rails.application.routes.draw做
root 'static_pages#welcome'
get 'wishlist' => 'static_pages#wishlist'
resources :rooms, only: [:index, :show] do
resources :reservations, only: [:create]
resources :reviews, only: [:create, :destroy]
end
resources :rooms do
put :favorite, on: :member
end
答案 0 :(得分:2)
在whishlist.html.erb中,您正在使用&#39; @ room&#39;而不是&#39; room&#39;。 @room仅在房间控制器中设置,而不是静态页面控制器。