Hello. We are currently setting up the association.

We are building a 1: many relationship with worker: lists and would like to display it if there is worker.user_name in lists/show.

But if workers do not exist

undefined method ʻuser_name'for nil: NilClass

Error has occurred and cannot be resolved.

References: worker is specified, and the following settings are also made in model.

belongs_to: worker
has_many: lists
def show
    @list = List.find (params [: id])
    @q = List.ransack (params [: q])
    @lists = @ q.result
    @prev_list = @ lists.where ("lists.id<?", @ List.id) .last
    @next_list = @ lists.where ("lists.id>?", @ List.id) .first
 def list_params
  params.require (: list) .permit (
    : company, # company name
  )&.merge (worker: current_worker)
 = @ list.worker.user_name

Is there a mistake in the above program?
I look forward to working with you.

  • Answer # 1

    Because it's Rails 5belongs_to: workerThen automatically
    existA validation of the worker_id setting for the worker is created.
    Despite this, if that happens, the possibility is

    List created before setting belogns_to

    It is a List that has no foreign_key setting in the DB and is inserted without passing through Rails (maybe it is defined because it is references: worker).

    So, delete those data as they will no longer occur (because it will be validated).

    For symptomatic treatmentworker&.user_nameThere is also a hand.