0

I have two models User and Want. A User has_many: Wants.

The Want model has a single property besides user_id, that's name.

In the edit action view in the UsersController there are two forms. One POSTs (PUT) to the UsersController update method to update the user, another POSTs to the WantsController create action to add a new Want to the user's account.

This is fine and I have it working, but...

In the create action of the WantsController I redirect back to the edit action of the UsersController to show success or Want validation errors.

The issue is that the edit action creates a new @want for the form and the validation errors are lost in the request.

Check out the create action in the UsersController:

def create
    @want = current_user.wants.build(params[:want])
    if @want.save
      flash[:success] = "WANT created!"
      redirect_to user_account_path current_user.username
    else
      #flash[:validation] = @want.errors <- I NEED THESE ERRORS FOR MY VIEW
      redirect_to user_account_path current_user.username
    end
  end

and the edit action of the UsersController:

def edit
  @want = @user.wants.build
  super
end

Because the WantsController redirects I lose the errors in the @want instance variable. I can store the errors in the flash (as shown in the comment) but surely this is a complete misuse of the flash.

So my question is, how can I persist those errors accross the action so I can render in my view the Want validation errors?

Also, is this considered a validation of Rails conventions? Seems a bit overkill to create a whole new page so a user can add a single want with one string property!

Thanks.

4

1 回答 1

0

在这种情况下渲染比重定向更常见:

if @want.save
  …
else
  @user = current_user
  render 'users/edit', status: 400
end

不过,这也有一些缺点:

  • 如果users/edit模板更改并需要额外的实例变量,您现在必须更改两个控制器操作。您可以通过使用包含渲染视图所需的所有内容的演示者对象来解决此问题。users/edit
  • 如果页面上有很多内容users/edit,用户可能很难发现他们试图纠正的错误。如果是这种情况,我会争辩说,添加一个wants/new仅显示用于创建新需求的表单的视图会简化问题。您始终可以wants/new部分.users/edit
于 2013-06-27T11:25:27.877 回答