1

我在理解为什么我无法使用包装器方法访问 Rails 中关联模型的属性时遇到了一些麻烦。我有一个模型规格失败,这是一个插图:

在此处输入图像描述

以下是相关文件的简短说明性列表:

event.rb

class Event < ActiveRecord::Base
  attr_accessible :author, :away_team_score, :details, :event_on, 
                  :home_team_score, :name, :title, :type, :home_team_id,
                  :away_team_id, :winner, :user_id

  validates_presence_of :author, :name, :title, :event_on, :type

  has_many :articles, dependent: :destroy
  has_many :medias, dependent: :destroy

  belongs_to :user
  belongs_to :home_team, class_name: "Team"
  belongs_to :away_team, class_name: "Team"

  scope :by_user, ->(user_id) {where(user_id: user_id).order("name")}
  scope :by_team, ->(team_id) {where(team_id: team_id).order("sport_type")}
  scope :by_score, -> {select(:home_team_score, :away_team_score, :winner)}
  scope :upcoming_events, -> {where("event_on >= ?", 1.minute.from_now)}
  scope :past_events, -> {where("event_on < ?", 1.minute.ago)}
  scope :recent, -> {where("event_on > ?", 3.days.ago).limit(3)}

  def winner
    if home_team_score > away_team_score
      home_team_name
    elsif home_team_score == away_team_score
      "#{home_team_name} #{away_team_name}"
    else
      away_team_name
    end
  end

  private
  def home_team_name
    home_team.name
  end

  def away_team_name
    away_team.name
  end
end

team.rb

class Team < ActiveRecord::Base
  attr_accessible :name, :sport_type, :university_id

  belongs_to :university

  validates_presence_of :name, :sport_type
end


event_spec.rb - only the failing spec.

context "a winning home team" do
  it "returns the home team name" do
    event = Event.new
    event.home_team_score = 20
    event.away_team_score = 10
    expect(event.winner).to eq event.home_team_name
  end
end

提前致谢!

4

2 回答 2

1

您可以使用 my_object.try(:method) :如果 my_object 为 nil,它不会引发错误

def home_team_name
  home_team.try(:name)
end

def away_team_name
  away_team.try(:name)
end

如果您想在没有关联客队/主队的情况下显示一个值,请使用双管道:

def away_team_name
  away_team.try(:name) || 'No away team associated'
end

另一种更明确的方法:

def away_team_name
  if away_team.present?
    away_team.name
  else
    'No away team associated'
  end
end

或简短版本:

def away_team_name
  away_team.present? ? away_team.name : 'No away team associated'
end
于 2013-10-25T16:13:44.717 回答
1

在您的规范中,您没有在活动和团队之间建立关联。你打电话来获得一个新的事件,但从来没有在任何团队Event.new之间建立联系。event所以,当然,home_team并且away_team在那个 Event 实例上都为零。

您需要在规范中进行更好的设置。

it "returns the home team name"  
  event = Event.new(home_team_score: 20, away_team_score: 10)
  event.home_team = Team.new(name: 'foo')
  expect(event.winner).to eq 'foo'
end
于 2013-10-25T16:25:23.480 回答