0

我正在创建一个应用程序,用户可以在其中收藏一个房间。我从 has_and_belongs_to_many 关联开始。但后来我才注意到,用 drestroy 实现删除按钮非常棘手。所以这次我决定通过关联使用 has_many。我有一个用户应该将房间添加到收藏夹或愿望清单。不幸的是,当我点击收藏按钮时,我收到了这个错误:

在此处输入图像描述

我缺少什么我怎样才能使这项工作?

如果您需要更多信息,请告诉我。我以此为方向。

在 Rails 3 和 4 中实现“添加到收藏夹”

最喜欢的房间.rb

class FavoriteRoom < ApplicationRecord
    belongs_to :room
    belongs_to :user
end

房间.rb

belongs_to :user
has_many :favorite_rooms  
has_many :favorited_by, through: :favorite_rooms, source: :user

用户.rb

 has_many :rooms
 has_many :favorite_rooms 
 has_many :favorites, through: :favorite_rooms, source: :room

路线.rb

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

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

显示.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 %>

create_favorite_rooms.rb(迁移文件)

class CreateFavoriteRooms < ActiveRecord::Migration[5.0]
  def change
    create_table :favorite_rooms do |t|
      t.integer :room_id
      t.integer :user_id

      t.timestamps
    end
  end
end
4

0 回答 0