class FavoritePhoto < ActiveRecord::Base
belongs_to :user
belongs_to :photo
validates :user_id, uniqueness: {
scope: [:photo_id],
message: 'can only favorite an item once'
}
end
PhotosController
def favorite
@photo = Photo.find(params[:id])
if request.put?
current_user.favorites << @photo
redirect_to :back, notice: 'You successfully favorited this photo'
else request.delete?
current_user.favorites.delete(@photo)
redirect_to :back, notice: 'You successfully unfavorited this photo'
end
end
<%= link_to favorite_photo_path("#{photo.id}"), method: :put do %>
<span class="glyphicon glyphicon-heart"></span>
<% end %>
resources :photos do
match :favorite, on: :member, via: [:put, :delete]
end
这可以防止用户多次使用同一张照片,并且错误消息“用户只能收藏一次项目”显示在我的Heroku日志中,但是,当他们尝试两次收藏照片时,没有重定向和消息向用户解释发生了什么,它只是在favorite_photo_path('#{photo.id}“)超时。
答案 0 :(得分:1)
array_values
这是迄今为止我唯一能够工作的人。
答案 1 :(得分:0)
我不完全确定最好的方法是在同一个动作中执行删除和更新,但是如果你想这样做,你可以这样做:
User
has_many :favorite_photos
PhotosController
def favorite
@photo = Photo.find(params[:id])
if request.put?
favorite = current_user.favorite_photos.new(photo: @photo)
if favorite.save
redirect_to :back, notice: 'You successfully favorited this photo'
else
redirect_to photo_path(@photo), notice: favorite.errors.full_messages
end
else request.delete?
current_user.favorites.delete(@photo)
redirect_to :back, notice: 'You successfully unfavorited this photo'
end
end
答案 2 :(得分:0)
问题在于,当它们是单独的抽象层时,您依靠ActiveRecord
验证来填充您的视图。
您需要包含某种条件逻辑,以确定@photo
是否通过了您设置的验证:
#app/controllers/photos_controller.rb
class PhotosController < ApplicationController
def favorite
@photo = Photo.find params[:id]
response = current_user.favorites << @photo if request.put?
response = current_user.favorites.delete @photo if request.delete?
if response.valid?
message = response.errors.full_messages.first
else
message = request.put? ? "You have successfully favourited this photo" : "You have successfully unfavourited this photo"
end
redirect_to @photo, notice: message
end
end