【发布时间】:2017-03-09 02:19:56
【问题描述】:
我已经使用 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
【问题讨论】:
标签: ruby-on-rails ruby controller routes