如何查看表单是否已填写在rails中?

时间:2017-06-04 22:36:47

标签: ruby-on-rails forms

我的userinfo模型和雇主模型中有函数,以查看是否已填写各自的表单。 现在,我的userinfo模型如下所示:

class Userinfo < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && email? && college? && gpa? && major?
    end

end

emloyer模型看起来像这样:

class Employer < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && company? && position? && number? && email?
    end
end

导航栏代码所在的layout / application.html.erb中的导航栏是:

        <% if user_signed_in? %>
            <%if current_user.employer(&:info_complete?) %>      
                <li><p>Employer form has been filled out</p></li>
            <%elsif current_user.userinfo(&:info_complete?) %>
                <li><p>Userinfo form has been filled out</p></li>
            <%else%>  
                <li><p>Nothing has been filled out</p></li>
            <%end%>  
            <li><%= link_to "Sign Out", destroy_user_session_path, method: :delete %></li>              
        <% else %>  
            <li><%= link_to "Log In", new_user_session_path %></li>
            <li><%= link_to "Sign Up", new_user_registration_path %></li>                  
        <% end %>

如您所见,这仅用于测试。我会显示一个句子,看看我的逻辑是否有效。

然后userinfo / new表单是这样的: enter image description here 雇主/新表格是:enter image description here

正如你在两张表格图片中看到的那样,在导航栏中,它表示当用户到达那里时表格已经填写完毕。没有输入任何信息。为什么它将“true”传递给“info_complete?”即使还没有输入数据,我的模型中的功能仍然存在?

1 个答案:

答案 0 :(得分:1)

这是你的模特......

user_info.rb

class Userinfo < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :name, :email, :college, :gpa, :major
end

employer.rb

class Employer < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :name, :company, :position, :number, :email
end

控制器。

employers_controller.rb

Class EmployersController < ApplicationController
  def new
    @employer = Employer.new
  end

  def create
    @employer = Employer.new(valid_params)
    respond_to do |format|
      if @employer.save
        format.html { redirect_to root_path }
      else
        format.html { render :new }
      end
    end
  end

  private 

  def valid_params
    params.require(:employer).permit(:name, :company, :position, :number, :email)
  end
end

<强>视图。 雇主/ new.html.erb

<%= render 'form' %>

雇主/ _form.html.erb

<% if @employers.errors.any %>
  <% @employers.full_messages.each do |m| %>
    <p><%= m %></p> 
  <% end %>
<% end %>

为user_info做同样的事情..