繁体   English   中英

将收藏夹添加到仅登录的用户,而不是所有用户

[英]Adding Favorite to Just the User logged in, not all Users

我正在使用 Rails 后端和 React 前端创建一个最喜欢的方法。 我试图让用户 select 一家咖啡店并收藏它,以便将其添加到他们自己的收藏夹列表中。 我的方法似乎正在添加,但是当用户添加咖啡店时,所有用户都可以在他们的收藏夹中看到它,而不仅仅是特定用户能够在他们自己的收藏夹列表中看到它......

我最喜欢的 Controller...

class FavoritesController < ApplicationController
    before_action :authorized, only:[:create, :update]
    def index
        favorites = Favorite.all 
        render json: favorites
    end

    def show
        favorite = Favorite.find_by(params[:id])
        render json: favorite
    end

    def create
        coffee_shop = CoffeeShop.find_or_create_by(:name => params[:coffee_shop_name]) do |coffee_shop|
            coffee_shop.image_url = params[:coffee_shop_image_url]
            coffee_shop.phone = params[:coffee_shop_phone]
        end
        favorite = Favorite.new
        favorite.user_id = @user.id
        favorite.coffee_shop_id = coffee_shop.id
        favorite.save
        render json: favorite
    end
  
    def update
        favorite = Favorite.find(params[:id])
        favorite.update(favorite_params)
        favorite.save
        render json: favorite
    end

    def destroy
        favorite = Favorite.find(params[:id])
        favorite.destroy
        render json: {message: "Successfully removed favorite"}
    end

    private

    def favorite_params
        params.require(:favorite).permit(:coffee_shop_id, :user_id, :coffee_shop_image_url)
    end
end

我的收藏夹代码组件/容器

import React from 'react'


class Favorite extends React.Component {
    
    state = {
    favorites:[],
    cafes:[],
    }
   

   handleDelete = (e) =>{
    const cafedelete = {
        coffee_shop_name: this.state.coffee_shop_name,
        coffee_shop_image_url: this.state.coffee_shop_image_url,
        coffee_shop_phone: this.state.coffee_shop_phone,
        coffee_shop_id: this.state.coffee_shop_id,
      }  
     this.props.removeFav(cafedelete)
    }
   
   render() {
       console.log(this.state.cafes.name)
        return (
        <div className="fav-card">
            <ul className="fav-ul">
             <img src={this.props.favorite.coffee_shop.image_url} className="fav-img"alt="cafe"></img>
            <div>{this.props.favorite.coffee_shop.name}</div>
        <div>{this.props.favorite.coffee_shop.phone}</div>
        {/* <button onClick={(e) => {this.handleDelete(e)}}>X</button> */}
        </ul>
        </div>
            )
        }
    }
    export default Favorite;

-------
import React from 'react';
import CoffeeShop from './CoffeeShop'
import NavBar from './NavBar'
// import coffeecup from './coffeecup.png'

class CafesContainer extends React.Component {

  state = {
    cafes: [],
    cafe:{},
    isCafeViewOn: false,
    inputValue: '',
    inputSort: '',
}

componentDidMount() {
  fetch("http://localhost:3000/search")
  .then(resp => resp.json())
  .then(cafes => this.setState({ cafes: cafes.businesses }))
}

addToFav = (cafe) => {
  console.log(cafe)
  fetch(`http://localhost:3000/favorites`,{
    method: "POST",
    headers: { 
      "Content-Type" : "application/json",
      Accept: "application/json",
      Authorization: `bearer ${localStorage.token}`
    },
      body: JSON.stringify( cafe )
  })
  .then(res => res.json())
  .then(console.log)
  }
  cafeFilterOnChange = (e) => {
    console.log (e.target.value)
    this.setState({
      inputValue: e.target.value,
      inputSort: e.target.value,
    });
  };


  
render() {  
  
  const filteredCafes =
  this.state.cafes.filter( cafe => {
    return cafe.name.toLowerCase().includes(this.state.inputValue.toLowerCase())
  })

  console.log(this.state.cafes)
    return (
      <div className="cafe-title"> 
       {/* <img className="cup" src={coffeecup} alt="cup" /> */}
       <NavBar />
      <label className="cafe-search"htmlFor="search">Search by Cafe Name</label>
      <br></br>
      
      <input type="text" className="cafe-search-bar" placeholder="Type Cafe Name Here..." value={this.inputValue} onChange={(e) => {this.cafeFilterOnChange(e)}}/>

      <ul>
        {
           filteredCafes.map(cafe => <CoffeeShop cafes={this.filteredCafes} handleCafeView={this.handleCafeView} cafeFilterOnChange={this.cafeFilterOnChange} inputValue={this.inputValue}
           addToFav={this.addToFav} key={cafe.id} cafe={cafe} />)
        }  
      </ul>
     </div>
    )
  }
}
;
  export default CafesContainer;

我正在使用 JWT 进行身份验证,我的 ApplicationController ...

class ApplicationController < ActionController::API
  # before_action :authorized, only:[:create]
  def encode_token(payload)
      JWT.encode(payload, "coffee")
  end 

def auth_header
  # { Authorization: 'Bearer <token>' }
  request.headers['Authorization']
end

def decoded_token
  if auth_header
    token = auth_header.split(' ')[1]
    # header: { 'Authorization': 'Bearer <token>' }
    begin
      JWT.decode(token,'coffee', true, algorithm: 'HS256')
    rescue JWT::DecodeError
      nil
    end
  end
end

def current_user
  if decoded_token
    user_id = decoded_token[0]['user_id']
    @user = User.find_by(id: user_id)
  end
end

def logged_in?
  !!current_user
end

def authorized
  render json: { message: 'Please log in' }, status: :unauthorized unless logged_in?
end
end

最近的新兵训练营毕业生,仍在努力寻找我的方式,如果需要任何其他信息,请告诉我,感谢任何帮助!

我怀疑而不是

def index
  favorites = Favorite.all 
  ...

你真的想要

favorites = current_user.favorites

如果您正在使用身份验证(例如设计)。

如果您尚未添加身份验证,则需要在您的 fetch 中发送一个 user_id 参数。

fetch('http://localhost:3000/favorites?user_id=___')

那么 controller 将是

favorites = Favorite.where(user_id: params[:user_id])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM