Accessing a has_one associations' attributes

后端 未结 4 531
暗喜
暗喜 2021-01-06 00:26

I\'m still quite new to Rails so hopefully this isn\'t a silly question.

I have two models: User and Chore. User has_one chore, and Chore belongs to User

<         


        
4条回答
  •  天命终不由人
    2021-01-06 01:04

    undefined method `name' for nil:NilClass

    This says that you are trying to call some method name() on an an instance of Nil. Within your code's context, that says that chore on this line is nil

    <%= user.chore.name %>
    

    Simply put, one of the User instances in @user has no associated Chore. One simple way to accomodate this in your view is by checking if user.chore exists.

    <%= user.chore.nil? ?  "some default name" : user.chore.name %>
    

提交回复
热议问题