我有一個非常適合類別和大喊之間的結構。我要做的就是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),但我仍然有一個疑問:要調用這個方法,如果有一個類將被創建?如果有的話只創建關係而不創建新關係? –