Это время для has_many:: через контроллер? И если да, то как это выглядит? - PullRequest
0 голосов
/ 22 января 2019

Я создаю приложение, которое позволяет пользователю отслеживать свои настольные игры. Существует мастер-библиотека для добавления настольных игр в личную библиотеку пользователя. Что-то в моем коде сделало эти две библиотеки более или менее синонимичными. Каждый раз, когда я сбрасываю и перенастраиваю свою базу данных, она автоматически добавляет все игры из основной библиотеки в пользовательскую библиотеку.

Но это не та проблема, с которой я хочу работать, это просто в том же духе. Когда я нажимаю на функцию axios.delete для удаления настольной игры из библиотеки персонажей, она также вызывает удаление настольной игры из основной библиотеки. Поскольку у меня настроен бэкэнд, у меня есть пользователи has_many board_games и board_games has_many. Я думаю, что мой axios.delete использует мою функцию уничтожения в общем контроллере board_game, а не user_board_games (хотя именно туда я его отправляю), и поэтому я думаю, что мне нужно создать контроллер, специфичный для user_board_games. Но мое исследование has_many through дает мне только самые базовые настройки.

Вот компонент:

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

1 Ответ

0 голосов
/ 23 января 2019

вам нужно установить 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, вот справочник по рельсам для получения более подробной информации и справочный образец , в основном это информирование рельсов о запросах на основе внешних ключ, сохраненный в UserBoardGames,

UserBoardGames будет иметь поля user_id и board_game_id, например, у пользователя с идентификатором 1 есть 2 настольные игры (id 2 и 3), UserBoardGames сохранит 2 записи следующим образом

| user_id | board_game_id |
|---------|---------------|
| 1       | 2             |
| 1       | 3             |

когда вы даете команду @ user.board_games, она сначала запросит 2 записи выше в UserBoardGame, а затем продолжит поиск записей BoardGame с идентификаторами 2 и 3, ключ здесь , соединение между пользователем и BoardGame: Запись UserBoardGame

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...