Pergunta

I'm attempting to create a view that displays multiple one-to-many associations. In my app, each "inspection" is assigned to a single "client" and "agent." I've setup my relationships. Agent is returning as it should be, however client is returning an undefined method nil:nilClass for "name."

# inspections_controller.rb

    def new
        @inspection = Inspection.new
        @agents = Agent.all
        @clients = Client.all

        respond_to do |format|
            format.html # new.html.erb
            format.json { render json: @inspection }
        end
    end 

# inspection.rb (model)

    belongs_to :agent
    belongs_to :client

# agent.rb (model)

    has_many :inspections

# client.rb (model)

    has_many :inspections

# index.html.erb (inspections view)

    <td><%= inspection.agent.name %></td> # works
    <td><%= inspection.client.name %></td> # returns undefined method `name'

I'm at a loss here, because the associations and tables are setup exactly the same. I'm able to return <%= inspection.client_id %> just fine.

Foi útil?

Solução

It is possible that you don't have a corresponding client for an inspection record that has a client_id. Maybe you manually deleted a client at some point? Check you data and also add checks to your code to ensure that you don't throw an error so something like this might help

 <td><%= inspection.client.name unless inspection.client.blank?%></td> # returns undefined method `name'

At least that way you will be able to get a visual idea of which inspections don't have corresponding clients making it easier for you to investigate why this might be

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top