我有一个非常适合类别和大喊之间的结构。我要做的就是qeuro在POST类型API的调用具有以下参数:在Ruby on Rails中创建一个包含多对多关系的帖子
{
"user_id":"1",
"title":"primeito",
"desciption":"de_novo",
"categories":[{"name":"eletro"},{"name":"domestic"},{"name":"new_category"}],
"yell_type":"novo",
"price":"10,00",
"payment_type":"boleto"
}
我的结构如下:
我的模型大喊:
#yell.rb
class Yell < ActiveRecord::Base
belongs_to :user, inverse_of: :yells
has_and_belongs_to_many :categories
end
模型类别:
#category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :yells
end
方法克里特控制器大喊:
#yells_controller.rb
def create
@yell = Yell.new(yell_params)
params[:categories].each do |rel|
@category = Category.find_by_name(rel[:name])
if @category
#only creates the relationship
else
@yell.categories.build(name: rel[:name]) #creates the relationship and category
end
end
if @yell.save
render json: @yell, status: :created, location: api_yell_path(@yell)
else
render json: @yell.errors, status: :unprocessable_entity
end
end
...
private:
def yell_params
params.require(:yell).permit(:title, :desciption, :price, :payment_type, :user_id, :yell_type, :categories)
end
所以我创建的表
class CreateCategoriesYellsJoinTable < ActiveRecord::Migration
def self.up
create_table :categories_yells, :id => false do |t|
t.integer :category_id
t.integer :yell_id
end
add_index :categories_yells, [:category_id, :yell_id]
end
def self.down
drop_table :categories_yells
end
end
我可以让他创建的类别,但不知道如何创建唯一的关系。 Agluem可以帮助我的评论#只是建立关系?
我需要,因为该类别名称是唯一
做此项检查同样,如果有人知道的东西更优雅的方式来做到这一点,我接受建议
然后,我创建的表,缺少的是@ yell.categories.build(category_params),但我仍然有一个疑问:要调用这个方法,如果有一个类将被创建?如果有的话只创建关系而不创建新关系? –