【问题标题】:undefined method `location' for #<Event::ActiveRecord_Associations_CollectionProxy:0x007f834658ea50>#<Event::ActiveRecord_Associations_CollectionProxy:0x007f834658ea50> 的未定义方法“位置”
【发布时间】:2015-06-03 01:23:28
【问题描述】:

我有两个模型:事件和位置。位置有_许多事件和一个事件属于_一个位置。位置具有称为“城市”的属性。在控制器中,我有以下代码:

@locations = Location.all.includes(:events)
@events = @locations.collect{|l| l.events}
@events.each do |event|
    puts "event is #{event.inspect}"
    puts "event location is #{event.location}"
end

我收到以下错误:

undefined method `location' for #<Event::ActiveRecord_Associations_CollectionProxy:0x007f834658ea50>

我知道所有事件都有一个位置,所以这应该有效。我如何让它发挥作用?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activerecord


    【解决方案1】:

    如果您的任何位置没有与之关联的事件,这将失败。 您可以尝试确保您的数组中没有 nil 元素:

    @locations = Location.all.includes(:events)
    @events = @locations.collect{|l| l.events}.
      flatten.
      reject{|e| e.nil?}
    @events.each do |event|
        puts "event is #{event.inspect}"
        puts "event location is #{event.location}"
    end
    

    【讨论】:

      【解决方案2】:

      您的@locations.collect 调用返回一个ActiveRecord_Associations_CollectionProxy 数组,这就是错误的原因。如果您需要,您可以从集合中选择第一个元素,如下所示:

      @events = @locations.collect{|l| l.events}
      @events.each do |event|
          puts "event is #{event.first.inspect}"
          puts "event location is #{event.first.location}"
      end
      

      或者你可以flattencollect 的结果为:

      @events = @locations.collect{|l| l.events}.flatten
      @events.each do |event|
          puts "event is #{event.inspect}"
          puts "event location is #{event.location}"
      end
      

      【讨论】:

      • 谢谢,我试过了,但我得到了 nil:NilClass 的“未定义方法‘位置’。我检查了一下,我的所有事件都不是 nil 并且已经定义了位置,所以我不确定为什么它会显示为 nil
      • 你尝试了哪一个?您还可以检查each 中的对象以确保它不是nil。另外,您如何检查事件不是nil
      【解决方案3】:
      @events = Event.includes(:location).select('events.*, locations.city')
      

      现在在视图中您可以访问位置的城市

      <% @events.each do |e|%>
        <%= e.city %>
      <% end %>
      

      【讨论】:

        猜你喜欢
        • 2015-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多