我剛開始使用 Ruby on Rails,我有一個用例,我需要將我的 Json 回應從呼叫映射回現有的 Ruby 模型。但是,有一些欄位不能直接映射。我有一個看起來像這樣的資源類:
class SomeClassResource
attr_reader :field
def initialize(attrs = {})
@field = attrs['some_other_field']
end
然后我有一個方法,如果some_other_field與特定字串匹配,則回傳 true,或者回傳 false,如下所示:
def some_method(value)
value == 'aString' ? true : false
end
然后我需要在我的視圖中顯示 true 或 false。什么是正確的做法?
謝謝
uj5u.com熱心網友回復:
首先,您應該將方法簡化為:
# app/models/some_class_resource.rb
def some_method(value)
value == 'aString'
end
然后要在視圖中顯示它,您首先需要在控制器中獲取值(進入視圖范圍內的實體變數):
# app/controllers/some_class_resources_controller.rb
class SomeClassResourcesController << ApplicationController
def show
resource = SomeClassResource.new
@true_or_false = resource.some_value('aString')
end
end
然后你會想要一個像這樣的視圖:
# app/views/some_class_resources/show.html.erb
<h1>My view</h1>
Was it true? <%= @true_or_false %>
您還需要show在路由檔案中使用適當的路由。
# config/routes.rb
resources :some_class_resources, only: [:show]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536875.html
