I am new to Ruby on Rails, and I would like to create a very simple website where I can save some citations.
I have several tables: Citation and Autor, here are the corresponding models.
class Citation < ActiveRecord::Base
belongs_to :autor
attr_accessible :text, :autor_id
end
class Autor < ActiveRecord::Base
has_many :citations
attr_accessible :name
end
I would like that when an user create a new citation that bellow to a new autor, the autor has to be automatically created.
Here is a part of my citations_controller:
def create
# Here I check if the autor already exist or not, if not, I create him (The user gave me his name)
if !(Autor.exists?(:name => params[:citation][:autor_id]))
Autor.create(:name => params[:citation][:autor_id])
end
#As I only have the name of the autor, I try to retrieve his Id
params[:autor_id] = Autor.where(:name => params[:citation][:autor_id]).first.id
@citation = Citation.new(params[:citation])
end
The point is, when I create a new citation, the field autor_id is filled with a 0 not with the correct ID of the autor. I think the mistake is when I try to retrieve the Id from the name, but I don’t know how to fix it, and perhaps there is a simpler solution !
Thank you !
while creating a new Autor save it in variable, then use this variable to get id
You can use this as
You can also use find_or_create method of rails which does the same as above.
After that if you want to create a citation you can also do:
this will create a citation with autor id and params[:citation] as its attributes