Store Join Model Data in Rails [duplicate]

心已入冬 提交于 2020-08-10 13:02:50

问题


I'm new to Ruby on Rails, and I'm developing a backend API.

Currently, I got 2 Active Record Models called Book and Genre.

Active Record Model

class Book < ActiveRecord::Base
    has_and_belongs_to_many :genres
end

class Genre < ActiveRecord::Base
    hast_and_belongs_to_many :books
end

DB Schema Model

create_table :books do |t|
  t.string "title"
end

create_table :genres do |t|
  t.string "genre"
end

create_join_table :books, :genres do |t|
  t.index [:book_id, :genre_id]
  t.index [:genre_id, :book_id]
end

REST POST Request

 # POST /book
    def create
        book= Book.new(books_params)

        if book.save
            render json: {status: 'SUCCESS', message:'Book Saved', data: book},status: :ok
        else
            render json: {status: 'ERROR', message: 'Booknot saved', data: book.errors}, status: :unprocessable_entity
        end 

    end

private
    def books_params
        params.require(:book).permit(:title)
    end

QUESTION

I'd like to make an HTTP Post request to create a new book with it's genres. I've already tested the book insertion (without genres, just passing the book name), it works perfectly. However I'd also like to add some genre categories.


回答1:


Both the has_many and has_and_belongs_to_many class methods create a set of _ids setters and getters:

book = Book.new
book.genre_ids = [1, 2, 3]
book.genre_ids == [1, 2, 3] # true

These setters will automatically create and delete rows in the join table. Since ActiveModel::AttributeAssignment maps the hash argument to .new, .update and .create to setters in the model all you need to do is whitelist the genre_ids parameter:

def books_params
  params.require(:book).permit(:title, genre_ids: [])
end

Passing an empty array permits an array of permitted scalar values like for example numericals or strings.



来源:https://stackoverflow.com/questions/63047441/store-join-model-data-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!