我正在创建一个应用程序,允许用户跟踪其棋盘游戏。有一个主库,用于将棋盘游戏添加到用户的个人库中。我的代码中的某些内容使这两个库或多或少成为了同义词。每次删除并迁移数据库时,它都会将所有游戏从主库自动添加到用户库。
但这不是我要处理的问题,它是相同的。当我点击axios.delete函数从人库中删除一个棋盘游戏时,它也触发了从母版库中删除该棋盘游戏。由于我目前已设置后端,因此我的用户has_many board_games和board_games has_many用户。我认为我的axios.delete在常规board_game控制器而不是user_board_games中击中了destroy函数(即使这是我发送的地方),所以我认为我需要创建一个特定于user_board_games的控制器。但是我对has_many的研究仅提供了最基本的设置。
以下是组件:
import React, { Component } from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import { Button, Card, Container, Dropdown, Grid } from 'semantic-ui-react'
class Games extends Component {
state = { games:[], user_games: [], showGames: false, sort: "A-Z" }
const userId = this.props.user.id
axios.get('/api/board_games')
.then(res => {
console.log(res.data)
this.setState({games: res.data});
})
axios.get(`/api/users/${userId}/board_games`)
.then(res => {
console.log(res.data);
this.setState({user_games: res.data});
} )
}
toggleGames = () => {
this.setState({ showGames: !this.state.showGames })
}
removeGame = (id) => {
const userId = this.props.user.id
axios.delete(`/api/users/${userId}/board_games/${id}`)
.then(res => {
console.log(res);
})
}
addGame = (id) => {
const userId = this.props.user.id
axios.post(`api/users/${userId}/board_games`, { userId, id })
.then(res => {
console.log(res);
})
}
dropDownMenu = () => {
return ( <Dropdown text='Sort'>
<Dropdown.Menu>
<Dropdown.Item text='A-Z' onClick={() => this.setState({sort: "A-Z"}) }/>
<Dropdown.Item text='Z-A' onClick={() => this.setState({sort: "Z-A"})} />
<Dropdown.Item text='Time Needed' onClick={() =>this.setState({sort: "Time Needed"})} />
</Dropdown.Menu>
</Dropdown>
)
}
userLibrary = () => {
const {user_games, sort} = this.state
switch(sort) {
case 'A-Z':
user_games.sort(function(game1, game2){
if(game1.title < game2.title) {return -1; }
if(game1.title > game2.title) {return 1; }
return 0;
});
break;
case 'Z-A':
user_games.sort(function(game1, game2){
if(game1.title > game2.title) {return -1; }
if(game1.title < game2.title) {return 1; }
return 0;
});
break;
case 'Time Needed':
user_games.sort(function(game1,game2){
return game1.time_needed-game2.time_needed
})
break;
default:
user_games.sort(function(game1, game2){
if(game1.title < game2.title) {return -1; }
if(game1.title > game2.title) {return 1; }
return 0;
});
}
return user_games.map( game =>
<Card key={game.id}>
<Card.Content>
<Card.Header>{game.title}</Card.Header>
<Card.Description>Players: {game.min_players} - {game.max_players}</Card.Description>
<Card.Description>Company: {game.company}</Card.Description>
<Card.Description>Time Needed: {game.time_needed}</Card.Description>
</Card.Content>
<Card.Content extra>
<Button basic color='red' onClick={() => this.removeGame(game.id)}>
Remove from Library
</Button>
</Card.Content>
</Card>
)
}
gamesList = () => {
//gives each game with a link to more info
const { games, user_games } = this.state
return games.map( game =>
<Card key={game.id}>
<Card.Content>
<Card.Header>{game.title}</Card.Header>
<Card.Description>Players: {game.min_players} - {game.max_players}</Card.Description>
<Card.Description>Company: {game.company}</Card.Description>
<Card.Description>Time Needed: {game.time_needed}</Card.Description>
</Card.Content>
{ user_games.include ? (
<Card.Content extra>
<Button basic color='green' onClick={() => this.addGame(game.id)}>
Add to Library
</Button>
</Card.Content>
)
: (
<Card.Content extra>
<Button basic color='red' onClick={() => this.removeGame(game.id)}>
Remove from Library
</Button>
</Card.Content>
)
}
</Card>
)
}
render() {
const { showGames } = this.state
return (
<Container>
<h1>Games</h1>
<Grid>
<Grid.Column floated="left" width={2}>
<h3>Your Games</h3>
</Grid.Column>
<Grid.Column floated="right" width={2}>
{this.dropDownMenu()}
</Grid.Column>
</Grid>
<Card.Group itemsPerRow={4}>{this.userLibrary()}</Card.Group>
{ showGames ? (
<div>
<Button basic onClick={this.toggleGames}>Done Adding</Button>
<Card.Group itemsPerRow={4}>{this.gamesList()}</Card.Group>
</div>
)
: (
<Button basic onClick={this.toggleGames}>Add a Game</Button>
)
}
</Container>
)
}
}
const mapStateToProps = state => {
return { user: state.user };
};
export default connect(mapStateToProps)(Games);
这是棋盘游戏控制器:
class Api::BoardGamesController < ApplicationController
before_action :set_board_game, except: [:index]
def index
render json: BoardGame.all
end
def show
render json: @board_game
end
def create
board_game = BoardGame.new(board_game_params)
if board_game.save
render json: board_game
else
render json: board_game.errors
end
end
def update
if @board_game.update(board_game_params)
render json: @board_game
else
render_error(@board_game)
end
end
def destroy
binding.pry
@board_game.destroy
end
private
def set_board_game
@board_game = BoardGame.find(params[:id])
end
def board_game_params
params.require(:board_game).permit(
:title,
:min_players,
:max_players,
:base_game,
:time_needed,
:company
)
end
end
棋盘游戏模型:
class BoardGame < ApplicationRecord
has_many :game_sessions, through: :game_session_games
has_many :users, through: :user_board_games
has_many :rounds
end
用户模型:
class User < ActiveRecord::Base
has_many :board_games, through: :user_board_games
has_many :game_sessions
# User.joins(:board_games).where("board_games.id == 'user.id'")
# Include default devise modules. Others available are:
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
include DeviseTokenAuth::Concerns::User
end
userBoardGame模型:
class UserBoardGame < ApplicationRecord
belongs_to :user
belongs_to :board_game
end
那么user_board_games_controller.rb中的内容是什么?
class Api::UserBoardGamesController < ApplicationController
def destroy
@user.board_game.destroy
end
end
答案 0 :(得分:0)
您需要在模型中将user_board_games设置为下面的示例代码
board_games模型
class BoardGame < ApplicationRecord
# I think you should mention user_board_games here
has_many :user_board_games, :dependent => :destroy
has_many :users, through: :user_board_games # you already had this line
end
与用户模型相同
class User < ActiveRecord::Base
# here is additional code
has_many :user_board_games, :dependent => :destroy
has_many :board_games, through: :user_board_games
end
如果您要断开某个用户与特定的board_games的连接,则可以通过UserBoardGamesController进行操作
class Api::UserBoardGamesController < ApplicationController
def destroy
# you need two inputs here user_id and board_game_id
@user = User.find(params[:user_id])
# here is why we set has_many for user_board_games above
@user_board_game = @user.user_board_games.find(params[:board_game_id])
@user_board_game.destroy
end
end
跟进问题,为什么User和BoardGame不得不提及has_many UserBoardGames,这里是rails guide reference for more detail and sample reference,基本上是为了通知Rails根据UserBoardGames中保存的外键进行查询,
UserBoardGames将具有user_id和board_game_id字段,例如具有ID 1的用户具有2个棋盘游戏(ID 2和3),UserBoardGames将保存2条记录,如下所示
| user_id | board_game_id |
|---------|---------------|
| 1 | 2 |
| 1 | 3 |
当您输入命令@ user.board_games时,它将首先在UserBoardGame中查询上面的2条记录,然后继续查找ID为2和3的BoardGame记录,此处的键是User和BoardGame之间的连接是UserBoardGame记录