【问题标题】:Accessing attributes of an object related model访问对象相关模型的属性
【发布时间】:2013-05-29 06:00:55
【问题描述】:

我最近开始在一个高尔夫网站上工作,遇到了一个我似乎无法理解的问题。我有两个模型,一个Event 模型和一个Round 模型。一个Event 设置有一个或多个Rounds

class Event < ActiveRecord::Base
    has_many :round

class Round < ActiveRecord::Base
    belongs_to :event

在我的主页中,我想显示下一个事件,然后显示与该事件相关的回合中的属性,例如start_timefees 等。在这种情况下,我们只玩一个为即将举行的活动轮流。

我能够获得下一个赛事,但我不明白如何访问与赛事相关的回合。

在我的HomeController 中,我有以下内容:

class HomeController < ApplicationController
    layout "home"

    def index
        @event = Event.next
    end
end

据我了解,拥有 has_many 和 belongs_to 关联将允许我在我的视图中使用 @event.rounds.start_time 之类的实例来获取与 @event 实例关联的回合的 start_time

我错过了什么?

谢谢,

备忘录

【问题讨论】:

    标签: ruby-on-rails ruby associations models


    【解决方案1】:

    @event.rounds 是一个数组。如果你想从数组中获取第一个元素的start_time -- 使用@event.rounds.first.start_time。或者您可以通过以下方式获取所有开始时间:@event.rounds.map(&amp;:start_time)

    还要在事件模型中将has_many :round 更改为has_many :rounds

    【讨论】:

    • 感谢 SD 的快速响应。我试过了,但我不断得到#<0x007f87b56e1e70>
    【解决方案2】:

    @Speransky Danil - 这不起作用,但我能够使用以下方法解决问题,尽管我觉得我对数据库有额外的调用。

    @event = Event.find(Event.next)

    正如我之前提到的,如果我通过 ID 进行查找,我可以访问与该事件相关的回合,但如果我尝试使用如下所示的范围,则无法访问。

    范围 :next, lambda { where('start_date >= ?', Date.today).limit(1) }

    这是我不断遇到的错误。

         NoMethodError: undefined method `rounds' for #<ActiveRecord::Relation:0x007fa40f3bdcf0>
    from /Users/Memo/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.13/lib/active_record/relation/delegation.rb:45:in `method_missing'
    from (irb):24
    from /Users/Memo/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
    from /Users/Memo/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
    from /Users/Memo/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
    

    我现在就继续这样做,以便继续并添加一个 TODO。

    【讨论】:

      【解决方案3】:

      我明白了。

      即使我限制为 1 条记录,我的事件调用 Event.next 也会检索一个数组。因此,基于此,我不得不将调用更改为:

      @event.first.rounds.first.start_time

      【讨论】:

        猜你喜欢
        • 2021-08-03
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 2013-12-25
        • 2022-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多