【问题标题】:How do I call a method on an instance object in rails?如何在 Rails 中调用实例对象的方法?
【发布时间】:2015-09-19 20:33:09
【问题描述】:

我有User 个人资料,而用户有Recordsbelong_to 用户。在我的users/show/1 路径中,如果用户有记录,我只想显示记录部分。所以,在我的 User 模型中,我写了一个方法:has_records?

def self.has_records?(usr)
  return true if User.find_by_id(usr.id).records.size > 0 
end

要调用这个方法,我需要在视图中写User.has_records?(user),确实是重复的。我可以重构代码以说@user.has_records?

【问题讨论】:

    标签: ruby-on-rails object view model instance


    【解决方案1】:

    如果你要在user模型中定义方法

    def has_records?(usr)
      self.find_by_id(usr.id).records.size > 0 
    end
    

    如果您想以has_records? 方法发送其他用户,它将起作用。如果你想检查同一个用户,那么

    def has_records?
      self.records.size > 0 
    end
    

    它应该可以工作

    【讨论】:

    • 像魅力一样工作!谢谢!
    • @MaximP 如果它有效,请您接受这个答案作为解决方案,谢谢
    • @Arv 我们在Ruby中一般使用隐式返回。我更新了你的回复。
    • @SimoneCarletti 我很抱歉我专注于这个问题谢谢
    【解决方案2】:

    当然,首先你需要将方法的类型从class method更改为instance method

    所以你在user model 中的方法就像

    def has_records?
      true if self.records.size > 0
    end
    

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      相关资源
      最近更新 更多