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?
on 09.05.2008 08:35
on 09.05.2008 18:57
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 :) 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/
on 10.05.2008 19:58
Julian Leviston 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 :) > > 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.