I have a very close relationship with the entities yell and category:
model yell.rb
class Yell < ActiveRecord::Base
belongs_to :user, inverse_of: :yells
has_and_belongs_to_many :categories
def as_json(options={})
super(:only => [:id, :title, :desciption, :price, :payment_type, :yell_type],
:include => {
:categories => {:only => [:id, :name]},
:user => {:only => [:id, :name]}
}
)
end
end
model category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :yells
def as_json(options={})
super(:only => [:id, :name],
:include => {
:yells => {:only => [:id, :title]}
}
)
end
end
migrate create_categories_yells_join_table.rb
class CreateCategoriesYellsJoinTable < ActiveRecord::Migration
def self.up
create_table :categories_yells, :id => false do |t|
t.belongs_to :category, index: true
t.belongs_to :yell, index: true
end
end
def self.down
drop_table :categories_yells
end
end
With this I made a crete
method where it will create my yell
and create category
if it does not exist and creates the relationship between the two. And if category
already exists it's just to create the relationship.
Then I make the following call POST
:
http://localhost:3000/api/yells
{
"user_id":"1",
"title":"mouse",
"desciption":"rato",
"yell_type":"demanda",
"price":"20,00",
"categories":[{"name":"tecnologica"}]
}
and it calls my method create
in controller_yells.rb:
def create
#@yell = Yell.new(yell_params.except(:categories))
@yell = Yell.new({title: params[:title], desciption: params[:desciption], price: params[:price], user_id: params[:user_id], yell_type: params[:yell_type]})
Array(params[:categories]).each do |rel|
@category = Category.find_by_name(rel[:name])
if @category
#cria apena o relacionamento entre a category e o yell
else
@yell.categories.build(name: rel[:name]) #creates the relationship and category
end
end
if @yell.save
render json: {status: 0, message:"sucess", data: @yell}, status: :created
else
render json: @yell.errors, status: :unprocessable_entity
end
end
It creates quiet everything right, but I do not know what to put in place of the comment #cria apena o relacionamento entre a category e o yell
.
Does anyone know how to do this or some more elegant solution?