Собираю свой "велосипед" по мотивам этого чудесного ответа. Но в моем случае и при создании и при удалении закладки юзером имею ошибки: -при создании advert_id остается пустым, -при удалении в вместо bookmark.id берется advert.id, что соответственно дает мне ошибку " ActiveRecord::RecordNotFound in AdvertsController#bookmark Couldn't find Bookmark with 'id'=1". где 1 это id объявления.
Где не прав? Заранее благодарен.
user model
has_many :adverts
has_many :bookmarks, dependent: :destroy
has_many :bookmark_adverts, through: :bookmarks, source: :advert
advert model
belongs_to :user
has_many :bookmarks, dependent: :destroy
has_many :bookmarks_user, through: :bookmarks, source: :user
bookmark model
belongs_to :advert
belongs_to :user
validates :advert_id, uniqueness: { scope: :user_id, message: 'has already been bookmarked' }
routes
resources :adverts, path: 'obyavleniya' do
# resources :bookmarks, only: [:create, :destroy]
put :bookmark, on: :member
end
adverts controller
class AdvertsController < ApplicationController
load_and_authorize_resource
before_action :authenticate_user!, except: [:index, :show]
before_action :load_advert, only: [:edit, :update, :destroy, :bookmark]
def index
@adverts = Advert.all
end
def show
end
def create
@advert = current_user.adverts.create(advert_params)
end
def edit
end
def update
end
def destroy
@advert.destroy
end
def bookmark
type = params[:type]
if type == "bookmark"
@bookmark = current_user.bookmarks.create(advert_id: params[:advert_id])
if @bookmark.save
redirect_to :back, notice: "You bookmark #{@advert.id}"
else
redirect_to :back, notice: "NO bookmark ;("
end
elsif type == "unbookmark"
current_user.bookmarks.delete(advert_id: params[:advert_id])
@bookmark = Bookmark.find(params[:id])
if @bookmark.destroy
redirect_to :back, notice: "Unbookmark #{@advert.id}"
else
redirect_to :back, notice: "NO Unbookmark ;("
end
else
redirect_to :back, notice: 'Nothing happened.'
end
end
private
def load_advert
@advert = Advert.find(params[:id])
end
def advert_params
params.require(:advert).permit(:title, :content, :user_id)
end
end
advert show views
- if current_user
= link_to "bookmark", bookmark_advert_path(@advert, type: "bookmark"), method: :put
= link_to "unbookmark", bookmark_advert_path(@advert, type: "unbookmark"), method: :put