Hello,
I am creating a new record in my Elements table and that is pretty
straight forward. But I need to add an ID to the Elements table that
comes from another model - Pages. How can I create a record in the
Pages table and then use its ID to populate the Elements table?
I was trying something like this in the ElementsController:
def create
@page = Page.new(params[:page])
@element = Element.new(params[:element])
if @element.save
flash[:notice] = ‘{@element.type.capitalize} was successfully
created.’
flash[:inform] = true;
render :partial => show
end
end
But no luck so far - any ideas?
Thanks!
I’m not sure I’m understanding this properly , but I think this should
work:
@page = Page.new( params[:page] )
if @page.save
@element = Element.new( params[ :element ] )
@element.page_id = @page.id
if @element.save
# do something
else
# element did not save, do something else
else
Page did not save
end
Sorry, I meant:
@page = Page.new( params[:page] )
if @page.save
@element = Element.new( params[ :element ] )
@page = Page.find( :last, :conditions => “title = #{@page.title}” )
@element.page_id = @page.id
if @element.save
# do something
else
# element did not save, do something else
else
Page did not save
end
Also, if the page title is not unique, you could try adding a created_on
field to the page table and then selecting only pages which have been
created in the last minute with the same title.
matt-beedle.com
best-mobile-phones.org
ok, so how about this?
@page = Page.new( params[:page] )
if @page.save
@element = Element.new( params[ :element ] )
@page = Page.find( :last, @page.title )
@element.page_id = @page.id
if @element.save
# do something
else
# element did not save, do something else
else
Page did not save
end
Thanks Matt! I’ll try that now…
On Dec 21, 12:00 pm, Matt B. [email protected]
Is this line really needed?
@page = Page.find( :last, :conditions => “title = #{@page.title}” )
@page already exists and should respond to @page.id and you will save a
search on the database.
–ABS