【问题标题】:Undefined Method - Multiple belongs_to associations未定义的方法 - 多个 belongs_to 关联
【发布时间】:2014-03-18 21:24:47
【问题描述】:

我正在尝试创建一个显示多个一对多关联的视图。在我的应用程序中,每个“检查”都分配给一个“客户”和“代理”。我已经建立了我的关系。代理正在按应有的方式返回,但是客户端正在为“名称”返回一个未定义的方法 nil:nilClass。

# 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'

我在这里不知所措,因为关联和表格的设置完全相同。我可以返回&lt;%= inspection.client_id %&gt; 就好了。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 relationship


    【解决方案1】:

    对于具有 client_id 的检查记录,您可能没有相应的客户端。也许您在某个时候手动删除了客户端?检查您的数据并在您的代码中添加检查以确保您不会抛出错误,所以这样的事情可能会有所帮助

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

    至少通过这种方式,您将能够直观地了解哪些检查没有相应的客户,从而使您更容易调查为什么会这样

    【讨论】:

    • 谢谢一百万。这正是问题所在。作为一个新手,Rails 试图返回一个没有与之关联的客户端的检查。添加除非语句允许我在需要的地方有空记录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多