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



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

我最喜欢的控制器。。。

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

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

如果您还没有添加auth,则需要在获取中发送一个user_id参数。

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

那么控制器将是

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

最新更新