Newbie Question: multiple models - need ID from one table to populate the other

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!

Walksalong wrote:

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?

def create
   @page = Page.new(params[:page])

      @page.save # it won't have an id until it's saved

   @element = Element.new(params[:element])

      @element.page_id = @page.id

   if @element.save
     flash[:notice] = '{@element.type.capitalize} was successfully
created.'
     flash[:inform] = true;
     render :partial => show
   end
end

hth,
Bill

Thanks Matt! I'll try that now...

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

Matt Beedle wrote:

Both work -- Thanks!