Rails 3 create default nested objects
I have a form where the user signs up and creates an Account, an User and a Website.
def new
@account = Acco开发者_开发问答unt.new
@account.users.build
@account.websites.build
...
end
def create
@account = Account.new(params[:account])
...
Everything works fine. Now, I want to create a default Page with Page.title = "homepage" and Page.body = "".
How can I do that? I tried different options and it doesn't work. For example, I do this @account.websites.pages.build
and I get this undefined method pages for []:ActiveRecord::Relation
.
The collection returned by @account.websites
is an array, rails can't intuit which member of the collection you're trying to create an associated object on... You need to specify which website you want to build a page for, ie
@account.websites.first.pages.build
精彩评论