On Apr 26, 8:33 am, Simon Arnaud <[email protected]> wrote: > Following the "chicken and egg problem with Models", I was wondering > if there was a way to create associated models easily without having > to use temporaries class. > > Lets say a simple thing as blog post and comments. > > class Post < Sequel::Model > many_to_one :author > one_to_many :comments > end > > class Author < Sequel::Model > one_to_many :posts > end > > class Comment < Sequel::Model > many_to_one :post > end > > Considering authors does not need to be created, I want to create a > post, with a few prefilled comments. > > I'm wondering if there are ways to code this as to construct the post > and the comments, and depending on user choice, commit it, or just > throw everything. Something like : > > post = Post.new(:title => "foo", :author => Author.first(:name => "whatever") > post.add_comment(:text => "...") > ask_user_if_ok do |response| > if reponse == 'ok' then > post.create > else > post.destroy > end > end > > I think transaction can solve this problem, but I'm not sure how I > would call it from sequel without the block syntax. > > Moreover, while this seems here very straightforward, the post might > be created (not in the database) well ahead of the comments. The > comments are attached through gui callbacks. And the user response is > from either a cancel or save button.
The nested_attributes plugin should work for what you are doing. If not, note that you can manually manipulate the association cache for each model object using the associations method: post.associations[:comments] = Author.new(...) post.associations[:comments] = [Comment.new(...), Comment.new(...)] You may need to do this instead of using the association methods themselves if you want to use objects that aren't in the database and don't want any modifications to the database. Jeremy -- You received this message because you are subscribed to the Google Groups "sequel-talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/sequel-talk?hl=en.
