【发布时间】:2017-06-04 22:36:46
【问题描述】:
我的用户信息模型和雇主模型中有函数来查看它们各自的表格是否已填写。 现在,我的 userinfo 模型如下所示:
class Userinfo < ActiveRecord::Base
belongs_to :user
def info_complete?
name? && email? && college? && gpa? && major?
end
end
雇主模型如下所示:
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 %>
如您所见,这只是为了测试。我显示一个句子,看看我的逻辑是否有效。
正如您在两个表单图片中看到的那样,在导航栏中,当用户到达那里时,它表示表单已被填写。没有输入任何信息。为什么它将“true”传递给“info_complete”?即使尚未输入数据,我的模型中的功能?
【问题讨论】:
-
你为什么要做 current_user.employer(&:info_complete?) 而不是 current_user.employer.info_complete?
-
如果我执行 .info_complete?,我会收到以下错误:“未定义的方法 `info_complete?'对于 nil:NilClass"
-
您应该验证在其控制器的
new操作中创建的@employer 和@info。还要检查验证guides.rubyonrails.org/active_record_validations.html -
@MahmoudSayed 你能解释一下吗?如何验证它们以及何时使用它们?
-
这些验证发生在保存您的实例之前(例如雇主)。您将表单字段发布到
create操作,然后执行employer.save,如果验证成功,则记录将保存到数据库中。您可以在create操作if employer.save then do something else render :new end中执行此操作,这应该会将您带回具有相同数据的表单字段,并且您可以显示此表单的错误。我建议阅读我在上述评论中发布的链接。
标签: ruby-on-rails forms