需要帮助以React / Rails应用程序实现CRUD和Many_to_Many关系

时间:2019-05-26 03:18:21

标签: ruby-on-rails activerecord many-to-many crud

我正在使用React / Rails-api组合创建抽认卡应用。该应用程序允许用户创建卡片组,创建卡片并将其分配给卡片组。开头为a deck has_many cardscards belongs_to deck。这是有问题的,因为如果删除卡组,则卡具有孤立的卡组ID作为属性。我还希望能够让用户在创建时从现有卡中进行选择。用户创建卡片时,必须将其分配给卡片组。

因此,我已通过连接表carddecksmany_to_many之间的关系更改为deck_cards。我可以找到与Deck.first.cardsCard.first.decks.的Deck / Card关系,我的主要问题是如何在React中通过获取请求来处理这种关系的CRUD操作?这是我当前获取请求以创建新Deck的示例:

 createDeck = (deckName) => {
     console.log(deckName)
     fetch('http://localhost:9000/api/v1/decks', {
       method: 'POST',
       headers: {
         'Content-Type': 'application/json',
         'Accept': 'application/json'
       },
        body: JSON.stringify({
          name: deckName, 
          user_id: '1'
        })
      })
      .then(res => res.json())
      .then(newDeck => {
        if (newDeck.errors) {
          alert(newDeck.errors) 
         } else {
           this.setState({ decks: [...this.state.decks, newDeck]})
         }
      });
    };

这是我的Rails / ActiveRecord模式:


ActiveRecord::Schema.define(version: 2019_05_25_235607) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "cards", force: :cascade do |t|
    t.string "front"
    t.string "back"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "deck_cards", id: false, force: :cascade do |t|
    t.integer "deck_id"
    t.integer "card_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "decks", force: :cascade do |t|
    t.string "name"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string "username"
    t.string "password"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

我的模特:

class Card < ApplicationRecord

    has_many :deck_cards, dependent: :destroy
    has_many :decks, through: :deck_cards

end
class Deck < ApplicationRecord
    has_many :deck_cards, dependent: :destroy
    has_many :cards, through: :deck_cards 
    belongs_to :user
end

class DeckCard < ApplicationRecord
  belongs_to :deck
  belongs_to :card
end


class User < ApplicationRecord
 has_many :decks
end


Being a noob, my brain has turned to mush trying to understand how to keep single source of truth so that Cards are not dependent on Decks and vice versa. How do I do CRUD action on the cards, decks and join table from React fetch CRUD requests?

0 个答案:

没有答案