用户#show中的NoMethodError - 无法识别关联对象(NilClass)

时间:2017-04-21 08:39:40

标签: ruby-on-rails ruby-on-rails-5

我收到了错误

  

nil的未定义方法`name':NilClass

用户/ show.html.erb

中的这行代码
<%= provide(:title, @profile.name) %>

我在个人资料模型(profile.rb)中定义了'name'

# return string of first and last name
def name
  "#{first_name} #{last_name}".titleize
end

这之前有效,所以我怀疑问题出在用户控制器中:

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

Eacher用户有一个个人资料。这也可能与我如何完成“注册”表单有关,该表单在用户注册表单中包含个人资料字段:

<%= form_for(@user, url: signup_path, id: "register_form", class: "form-horizontal" ) do |f| %>
          <%= render 'shared/error_messages' %>
            <div class="form-group">
              <h4>Account information</h4>
              <%= f.label :email, class: 'col-sm-2 control-label' %>
              <div class="col-sm-10">
                <%= f.email_field :email, class: 'form-control', placeholder: "john@example.com" %>
              </div>
              <%= f.label :password, class: 'col-sm-2 control-label' %>
              <div class="col-sm-10">
                <%= f.password_field :password, class: 'form-control', placeholder: "A-Z,a-z,0-9" %>
              </div>
              <%= f.label :password_confirmation, "Confirm password", class: 'col-sm-2 control-label' %>
              <div class="col-sm-10">
                <%= f.password_field :password_confirmation, class: 'form-control', placeholder: "Confirm password" %>
              </div>
            </div>

        <%= f.fields_for :profile do |p| %>

            <div class="form-group">
              <h4>About You</h4>
              <%= p.label :first_name, class: 'col-sm-2 control-label' %>
              <div class="col-sm-10">
                 <%= p.text_field :first_name, class: 'form-control', placeholder: 'First Name' %>
              </div>
            </div>


  <!-- more profile fields here, removed for brevity -->

        <% end %> <!-- fields_for @user.profile -->
      <%= f.submit "Create my account", class: "btn btn-primary" %>
    <% end %> <!-- form_for @user -->

0 个答案:

没有答案