1

我在我的 Rails 4.2 应用程序中使用了响应者gem。我遇到了一个非常复杂的情况,在Organization模型编辑视图中,我得到了一个OrganizationUser带有一个输入的表单。将用户添加到组织会调用create. OrganizationUsersController我在那里使用响应者进行重定向操作,如下所示:

def create
  @organization_user = @organization.organization_users.create(organization_user_params)
  respond_with @organization_user do |format|
    format.html { redirect_to edit_organization_path(@organization) }
  end
end

还有我的翻译:

flash:
  actions:
    create:
      notice: '%{resource_name} was successfully created.'
      alert: '%{resource_name} could not be created.'
  organization_users:
    create:
      notice: "Member has been added"
      alert: "Validation error"

问题是,如果资源有效并且持久化到数据库,那么一切正常。我被重定向到编辑组织视图并带有适当的通知消息,但如果验证失败,我将被重定向而没有任何警报。

我当然可以设置闪光警报消息,除非@organization_user被持久化,但这就是使用响应器自动设置闪光的全部意义所在。

4

3 回答 3

2

好的,我想通了。事实证明,由于验证错误,flash 被正确设置,但它是在flash 被删除之后flash.now代替的。解决方案是这样使用:flashredirect_to:flash_now => false

respond_with(@organization_user, :flash_now => false) do |format|
  format.html { redirect_to edit_organization_path(@organization) }
end
于 2015-02-27T15:16:46.637 回答
1

尝试:

respond_with @organization_user do |format|
  if @organization_user.valid?
    format.html { redirect_to edit_organization_path(@organization) }
  end
end
于 2015-02-27T14:30:34.097 回答
1

请注意,要使您的闪光灯config/locales/en.yml正常工作,您需要responders :flash在控制器的顶部。

于 2017-09-18T15:22:29.503 回答