添加到收藏夹时,为什么我在控制器中遇到SQLite3 :: ConstraintException?根据Hartl教程收集微博

时间:2016-03-29 11:42:25

标签: ruby-on-rails ruby sqlite

我在Hartl的关注用户按钮上建立了一个微博按钮。

我可以访问用户的页面,并且最喜欢一次微博,但是一旦我尝试收藏一秒钟,我就会在SQLite3::ConstraintException中获得FavouritesController#create。约束是:

UNIQUE constraint failed: favourites.favouriter_id, favourites.favourited_id.

为什么我遇到这种约束?

收藏控制器:

class FavouritesController < ApplicationController
before_action :logged_in_user

def create
@micropost = Micropost.find(params[:favourited_id])
current_user.favourite(@micropost)
redirect_to user_path (current_user)
end

def destroy
@micropost = Favourite.find(params[:id]).favourited
current_user.unfavourite(@micropost)
redirect_to user_path (current_user)
end  

end

添加到收藏夹表格:

<%= form_for(current_user.favourites.build) do |f| %>
  <div><%= hidden_field_tag :favourited_id, @user.id %></div>
  <%= f.submit "Favourite" %>
<% end %>

用户模型:

has_many :favourites, class_name: "Favourite",foreign_key:"favouriter_id", dependent: :destroy
has_many :favouriting, through: :favourites, source: :favourited

def favourite(micropost)
favourites.create(favourited_id: micropost.id)
end

def unfavourite(micropost)
    favourites.find_by(favourited_id: micropost.id).destroy
end

def favouriting?(micropost)
   favourites.include?(micropost)
end

用户控制器:

def favouriting
@title = "Favourites"
@user = User.find(params[:id])
@microposts = @user.favouriting.paginate(page: params[:page])
render 'microposts/show_favourite'
end  

def favouriter
@title = "Favourite"
@micropost = Micropost.find(params[:id])
@users = @micropost.favouriter.paginate(page: params[:page])
render 'microposts/show_favourite'
end 

Micropost模型:

class Micropost < ActiveRecord::Base
belongs_to :user

has_many :favourites, class_name: "Favourite",foreign_key: "favourited_id", dependent: :destroy
has_many :favouriter, through: :favourites, source: :favouriter

0 个答案:

没有答案