簡體   English   中英

Rails 4如何在實例方法中訪問模型屬性

[英]Rails 4 How to access model attributes in instance method

我遇到了一個看似簡單的問題,但我無法弄清楚問題是什么。 我正在使用Rails 4構建API。

我有一個叫做Constant的模型

class Constant < ActiveRecord::Base

  def self.calcuate_something(a, b, c, d, e)
    self.number_one + self.number_two + (self.number_three*a) + (self.number_four*b) + (self.number_five*c) + (self.number_six*d) + (self.number_seven*e)
  end

end

此模型具有屬性number_onenumber_twonumber_threenumber_fournumber_fivenumber_sixnumber_seven

在我的控制器中,我正在這樣做:

@constant = Constant.find_by_id(params[:id])
number = @constant.calculate_something(1, 2, 3, 4, 5)

然后我得到一個錯誤,提示NoMethodError (undefined method 'number_one' for #<Class:0x007fd3d4466068>): 我沒有嘗試訪問一個名為number_one的方法,而是試圖在模型中找到該字段。

我已驗證所有條目都有一個名為number_one的列,並且每個條目都有一個值。 我的語法或設置有問題嗎?

提前致謝!

問題在於您對self.calculate_something(a, b, c, d, e) 使用關鍵字self實際上是在創建類方法而不是實例方法,因此無法訪問這些屬性。

嘗試將其重構為def calculate_something(a, b, c, d, e)

評論更新:

第二個問題是@constant被分配給Constant.find_by_id(params[:id])生成的ActiveRecord_Relation而不是記錄實例,因為rails直到必要時才會自動評估查詢。 可以通過將find_by_id更改為find來解決此問題,或通過Constant.find_by_id(params[:id]).first強制執行查詢。 就個人而言,我喜歡更改以find所需的特定記錄。

閱讀Ruby中的類和實例方法 ,您想要將對象的方法定義為沒有self.實例方法self.

def calculate_something(a, b, c, d, e)

但是,如果要定義類方法,則需要使用self

不要使用find_by_id ,您需要使用find ,如下所示:

@constant = Constant.find(params[:id])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM