[英]Rails what is this variable(an object, a hash, an array, etc) and how can I access it?
我正在使用Rails應用程序,正在嘗試訪問此變量,並且不斷收到未定義的方法錯誤等。
在我的控制器中,我正在做:
@application = Application.find(params[:id])
@curr_app_id = @application.application_field.last(1)
puts @curr_app_id
它打印出來
#<ApplicationField:0x56678b8>
這是什么類型的變量,我如何訪問它的ID?
我在IRB控制台中做了一些調查...
1.9.3p0 :018 > puts User.last(1).class # => Array
1.9.3p0 :019 > puts User.last.class # => User
1.9.3p0 :018 > puts User.last(1) # => #<User:0x00000006f36280>
1.9.3p0 :019 > puts User.last # => #<User:0x00000006f36280>
相同的輸出,不同的類 !
給last
方法一個整數(即使您給出1)也會在此處產生Array: Class Array(Ruby 1.9.3) 。
1.9.3p0 :028 > puts User.last(1).id
# => NoMethodError: undefined method `id' for #<Array:0x00000006f2d8d8>
您應該使用last不帶參數:
@application = Application.find(params[:id])
@curr_app_id = @application.application_field.last
# then you should be able to use the object's methods:
puts @curr_app_id.id
@application.application_field.last
返回一個ApplicationField
對象。 將整數傳遞給#last
將返回數組中的對象數。
因此, @application.application_field.last(2)
將返回數組中與@application
關聯的最后兩個application_field對象。
@application.application_field.last
應該給您ApplicationField
對象。 在其上調用#id
@application.application_field.last.id
,應假定該ID是ActiveRecord模型(或其他方式,則是respond_to?(:id)
應返回該ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.