5 phương pháp thường gặp trong mô hình và helper:
Lựa chọn 1:
You can just define the method inside the Client class, and then call it from the view,
like this:
class Client < ActiveRecord::Base
def self.my_class_method
end
def my_instance_method
end
end
And then in your view:
<%= Client.my_class_method %>
<%= @client.my_instance_method %>
Phương án 2:
module MyModule
def my_method
end
end
Include the module in ApplicationHelper so it is available to all your views:
module ApplicationHelper
include MyModule
end
Then in your view you can call it easily:
<%= my_method %>
tùy chọn 3:
module MyModule
def my_method(amount)
end
end
In your model:
class Client < ActiveRecord::Base
include MyModule
def self.other_method(amount)
my_method(amount)
end
end
Then in your view you can call it easily:
<%= Client.other_method(amount) %>
Lựa chọn 4: Hoặc bạn có thể khai báo các phương thức helper như một chức năng lớp, và sử dụng nó như vậy:
module Myhelper
def self.my_village
"bikharniyan kallan,Rajasthan,India"
end
end
Then in your view you can call it easily:
<%= Myhelper.my_village %>
tùy chọn 5: sử dụng nhiều helper trong điều khiển helper =>
module Myhelper
def my_info
"my information is"
end
end
module Myhelper1
def my_village
"bikharniyan kallan,Rajasthan,India"
end
end
ApplicationHelper=>
module ApplicationHelper
include Myhelper
include Myhelper1
end
ApplicationController
class ApplicationController < ActionController::Base
include ApplicationHelper
end
YourController
class YourController < ActionController::Base
def action
my_info
my_village
end
end
Không , đó là một thực tế tồi tệ. Người trợ giúp được coi là người xem ** xem **, nếu bạn cần thứ gì đó từ người trợ giúp trong mô hình của bạn, nó có thể bị lẫn lộn với chế độ xem của bạn. –
Cảm ơn! Bạn làm cho tôi nhận ra rằng tôi cần phải gọi Client # my_method trong tầm nhìn của tôi ... Tôi đã nhìn chằm chằm vào mã này quá dài ... – Coderama
Chức năng của bạn phụ thuộc là gì? Ví dụ, nó sử dụng 'request' hoặc' params'? –