在Rails中存储联接模型数据 [英] Store Join Model Data in Rails
问题描述
我是Ruby on Rails的新手,并且正在开发后端API.
I'm new to Ruby on Rails, and I'm developing a backend API.
目前,我有两种Active Record模型,分别是 Book 和 Genre .
Currently, I got 2 Active Record Models called Book and Genre.
class Book < ActiveRecord::Base
has_and_belongs_to_many :genres
end
class Genre < ActiveRecord::Base
hast_and_belongs_to_many :books
end
数据库架构模型
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请求
# 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
问题
我想发出HTTP发布请求,以使用类型创建一本新书.我已经测试过书的插入(没有类型,只传递书名),它可以完美地工作.不过,我也想添加一些流派类别.
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.
推荐答案
两者 has_many
和has_and_belongs_to_many
类方法创建一组_ids
setter和getter:
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
这些设置器将自动创建和删除联接表中的行.由于 ActiveModel :: AttributeAssignment 将哈希参数映射到.new
,.create
设置模型中的设置器,只需将genre_ids
参数列入白名单:
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.
这篇关于在Rails中存储联接模型数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!