视图状态中的模型def

时间:2012-10-13 03:35:14

标签: ruby-on-rails ruby

在我的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”

有什么问题?

3 个答案:

答案 0 :(得分:0)

#current_playing_sport是PlaySport模型实例的方法。 current_user.play_sports将(根据命名判断)返回一组PlaySport实例。所以,你想要遍历它们并在每个上调用#current_playing_sport

答案 1 :(得分:0)

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

play_sports将返回集合,因此您可以使用map或类似

来调用该方法
current_user.play_sports.map &:current_playing_sports

也要记住,这将再次返回数组,该数组将为每个PlaySport模型提供current_playing_sports方法的结果。

答案 2 :(得分: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

这应该解决你所有的问题。