【问题标题】:Routes/Controller issues with "unfavorite action"带有“不喜欢的操作”的路由/控制器问题
【发布时间】: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


    【解决方案1】:

    在 whishlist.html.erb 中,您使用的是“@room”而不是“room”。 @room 仅设置在房间控制器中,而不是静态页面控制器。

    【讨论】:

    • 感谢分配!看不到这个!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2013-11-14
    相关资源
    最近更新 更多