[Rails] Re: Create several models at once and validating

Eduardo Yáñez Parareda eduardo.yanez at gmail.com
Thu Aug 17 07:06:32 GMT 2006


> This is bad. Your model should not be dependent on the View or the
> Controller - by using the params hash in your model code, you are
> restricting your model to only work in a request context. 

Yes, you're absolutely right, I've already change it.

> class UserController
> def create
>     @user = User.new(params[:user])
>     @team = Team.new(params[:team])
>     User.transaction do
>       success = @user.save
>       success &= @team.save
>       if success
>         flash[:notice] = 'User was successfully created.'
>         redirect_to :action => 'list'
>       else
>         render :action => 'new'
>       end
>     end
>   end

But I don't want this behaviour. I forgot to mention that User and Team 
are related:

User                              Team
  has_one :team <-------------->    belongs_to :user

Thus I did @user.team = @team then @user.save that saves my user and the
related team too.

But if I do @user.save and then @team.save, whether validations on team 
failed,
the user is created but team doesn't and I want non of them to be saved.


-- 
Posted via http://www.ruby-forum.com/.


More information about the Rails mailing list