-1

在我的模型中的 ruby​​ on rails 项目中,我有一些定义。

class PlaySport < ActiveRecord::Base
  belongs_to :user
  belongs_to :sport

  def self.getLevel
  end  

  def self.check_play_sport(cuser_id,sport_id)
  end  

  def current_playing_sports
  end

  def all_played_sports
  end

end

我抓住这样的关系

current_user.play_sports.current_playing_sports

但我得到未定义的方法错误“current_playing_sports”

怎么了?

4

3 回答 3

0

#current_playing_sport是 PlaySport 模型实例上的方法。current_user.play_sports将(根据命名判断)返回一组 PlaySport 实例。因此,您需要遍历它们并调用#current_playing_sport它们。

于 2012-10-13T03:45:40.413 回答
0

play_sports 是一个关联,因此您不能调用 PlaySport 模型中定义的实例方法。

play_sports 将返回集合,因此您可以使用 map 或类似的方法调用该方法

current_user.play_sports.map &:current_playing_sports

还要记住这将再次返回数组,该数组将具有每个 PlaySport 模型的 current_playing_sports 方法的结果。

于 2012-10-13T03:48:57.360 回答
0

首先,您尝试在 play_sport 对象数组上调用 current_playing_sports 方法。

您需要在每个 play_sport 对象上调用该方法,

就像是,

current_user.play_sports.collect(&:current_playing_sports)

我的疑问,

您已经定义了一个名为“current_playing_sport”的方法,并且您正在尝试访问“current_playing_sports”。我想你需要修正错字

您需要定义一个 has_many 关系。

在你的模型中,添加这个。

has_many :current_playing_sports

这应该可以解决您的所有问题。

于 2012-10-13T04:12:59.963 回答