lundi 11 septembre 2017

Favourite Model #No route match

I got this error

No route matches {:action=>"favorite", :controller=>"microposts", :id=>#, :type=>"favorite"} missing required keys: [:id]

Models:

class User< ApplicationRecord  
  has_many :microposts,dependent: :destroy
  has_many :favorite_microposts
  has_many :favorites, through: :favorite_micoposts, source: :micropost    
end

class Micropost < ApplicationRecord  
  has_many :favorite_microposts
  has_many :favorited_by, through: :favorite_microposts, source: :user
end         


class FavoriteMicropost < ApplicationRecord
  belongs_to :user
  belond_to :micropost
end

Micropost Controller:

class MicropostsController < ApplicationController
...
def favorite
 @micropost = Micropost.find(params[:id])  
 type = params[:type]
 if type == "favorite"
   current_user.favorites << @micropost
   redirect_to :back, notice: 'You favorited #{@micropost.number}'

 elsif type == "unfavorite"
   current_user.favorites.delete(@micropost)
   redirect_to :back, notice: 'Unfavorited #{@micrpost.number}'

 else
   # Type missing, nothing happens
   redirect_to :back, notice: 'Nothing happened.'
   end
  end
 end

Routes:

Rails.application.routes.draw do
resources :microposts do  
    match :favorite, on: :member, via: [:put, :delete]
  end
end

View:

<% if current_user %>
<%= link_to "favorite",   favorite_micropost_path(@micropost, type:"favorite"), method: :put%>
<%= link_to "unfavorite", favorite_micropost_path(@micropost, type: "unfavorite"), method: :put %>
<%end%>

Aucun commentaire:

Enregistrer un commentaire