Has_many/belongs_to question

Is it possible to automatically add data to the belongs_to end of a
hm/bt relationship?

For clarity, here are my models:

class Page; has_many :links; end
class Link; belongs_to :page; end

Is there anyway that I can do something like this:

Page.create( :name => ‘foo’, :links => [{:name => “bleh”, :url =>
www.bleh.com”}, {:name => “blah”, :url => “www.blah.com”}] )

Right now I am doing something like this in my controller:

def create
@page = Page.new(params[:page])
links = params[:links]
if @page.save
links.each{|e| @page.links.create(:name => e[:name], :url =>
e[:url])
end
end

But I feel there must be a more intuitive way of doing this.
Basically, I want to add my links collection (from a form at /pages/new)
to the page hash and create them automatically. Is this possible?

Hi,

I think you can say:

if @page.save
@page.links.create(params[:links])
end

I think that’s a happier way to say it :slight_smile:

Julian.

Learn Ruby on Rails! Check out the FREE VIDS (for a limited time)
VIDEO #4 parts a and b now available!
http://sensei.zenunit.com/

Julian L. wrote:

Hi,

I think you can say:

if @page.save
@page.links.create(params[:links])
end

I think that’s a happier way to say it :slight_smile:

Julian.

Learn Ruby on Rails! Check out the FREE VIDS (for a limited time)
VIDEO #4 parts a and b now available!
http://sensei.zenunit.com/

I have a feeling that;

@page = Page.new(params[:page])
@page.links = params[:links]
@page.save

will do all the saves in a nice transaction,
returning false, and having created no objects if any of the validation
fails.

Haven’t got anything set up to try it though.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs