【问题标题】:rendering the partials in controller after the validation check验证检查后在控制器中渲染部分
【发布时间】:2015-06-22 23:36:04
【问题描述】:

对于两种不同的注册表单,我有两个部分视图。在我的主页上,根据单击的链接,我正在呈现相应的表单。(视图/应用程序/索引)

= link_to 'Mentor', new_user_path(user_role: true), :class =>'btn'
= link_to 'Mentee', new_user_path, :class =>'btn'

在 views/users/new.html.haml 中,我正在检查用户角色并重定向到相应的表单。

- if params[:user_role]
= render 'mentor'
- else
= render 'mentee'

在用户模型中,我添加了这样的验证。

class User < ActiveRecord::Base
    email_regex = /\A[\w+\-.]+@cisco.com/i

    validates :cisco_email, :presence   => true,
              :format     => { :with => email_regex,}
    validates :work_city, :presence => true

end

因此,当有任何无效字段时,我想通过一条消息将其定向到同一个表单。我的控制器看起来像这样。

class UsersController < ApplicationController

   def index
   end

    def show
      @user = User.find(params[:id])
    end

   def new
     @user = User.new
    end

    def create
        @user = User.new(params[:user])    # Not the final implementation!
        if @user.save
            flash[:success] = "Welcome to the CSG Mentoring Tool!"
            redirect_to @user
        else 
        flash[:notice] = "Error regsitering."

             if params[:user][:user_role]
                      render :partial => 'users/mentor'
             else
                render :partial => 'users/mentee'
             end
         end
     end    
 end

当存在无效字段条目时,无论在哪个页面发生错误,它都会重定向到“受指导者”页面。整个css样式也改变了,flash也没有显示

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model-view-controller


    【解决方案1】:

    为什么这不起作用? 如果参数[:user][:user_role] 渲染:partial => '用户/导师' 别的 渲染:partial => '用户/学员' 结束

    params[:user][:user_role] 为零。

    您可以通过多种方式对其进行检查:

    高于你的 if 条件raise params[:user].inspect

    为什么是零?

    原因是你传递了new_user_path(user_role: true) user_role true,但 user_role 在导师形式中不是 true。

    params[:user_role] 不会在导师表单中设置user_role = true 字段。

    设置用户角色

    &lt;%=f.hidden_field :user_role, value: params[:user_role] %&gt;

    如果它应该对导师总是正确的

    &lt;%=f.hidden_field :user_role, value: true %&gt;

    默认情况下,flash 将使它们可用于下一个请求,但有时您可能希望在同一个请求中访问这些值。 Reference

    这适用于重定向

    flash[:success] = "Welcome to the CSG Mentoring Tool!"
    

    这将适用于渲染

    flash.now[:success] = "Welcome to the CSG Mentoring Tool!"
    

    【讨论】:

    • 谢谢@pradeep。我想知道如何以指导形式设置 user_role = true 以免发生这种情况。有什么方法可以引导我进入?
    • 谢谢@pradeep。但是我仍然想知道为什么当我从控制器渲染部分时整个布局会发生变化。
    • render 不要重新加载 css 和 js。这取决于您在应用程序中如何使用 css 和 js。在看到您的部分以及您如何包含 css 和 js 之后,很容易回答......
    • @pradeep。我的布局文件夹中有 application.html.haml。我有一个基本的 js 和 css 并将它们链接到 application.html.haml 文件。当我检查部分的源代码时,我正在渲染布局(链接到 jjs 和 css)丢失。
    • @pradeep。我刚刚浏览了几篇关于渲染局部的帖子并找到了解决方案。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2014-11-02
    • 2020-04-11
    • 2015-08-01
    相关资源
    最近更新 更多