实施"添加到收藏夹"

时间:2016-10-26 10:42:19

标签: ruby-on-rails has-many-through favorite

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

enter image description here

我错过了如何才能完成这项工作?

如果您需要更多信息,请告诉我。我用这个作为方向。

Implement "Add to favorites" in Rails 3 & 4

favorite_room.rb

class FavoriteRoom < ApplicationRecord
    belongs_to :room
    belongs_to :user
end

room.rb

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

user.rb

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

的routes.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

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 %>

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

0 个答案:

没有答案