Accessing a has_one associations' attributes

后端 未结 4 500
暗喜
暗喜 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:08

    Here's another option that uses Rails' Delegate module:

    class User < ActiveRecord::Base
      has_one :chore
      delegate :name, to: :chore, prefix: true, allow_nil: true
    end
    

    This will allow you to call <%= user.chore_name %>, which will pass the name call onto chore, returning nil if there is none.

提交回复
热议问题