问题
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