[英]Rails: Allowing different views in model to access controller
I'm new to Rails and have a RESTful controller for my Finance model: 我是Rails的新手,对于我的Finance模型有一个RESTful控制器:
finances_controller.rb finances_controller.rb
def index
@finances = Finance.find_all_by_user_id current_user[:id] if current_user
end
def spending
@finances = Finance.find_all_by_user_id current_user[:id] if current_user
end
This allows me to get my finances models on both index.html.erb and spending.html.erb . 这使我可以同时在index.html.erb和支出 .html.erb上获取财务模型。
However, I'd like to also add in some shared logic into both of these, such as: 但是,我还想在这两者中添加一些共享逻辑,例如:
def index
@finances = Finance.find_all_by_user_id current_user[:id] if current_user
finance = current_user.finance
@essentials = finance.rent.to_i +
finance.mortgage.to_i +
finance.gas.to_i +
finance.groceries.to_i +
finance.carpayment.to_i +
finance.carinsurance.to_i +
finance.othertransit.to_i +
finance.electric.to_i
end
This means I'd have to copy this logic onto both the def index and def spending methods, which doesn't seem right. 这意味着我必须将此逻辑复制到def索引和def支出方法上,这似乎不太正确。 Is there a better way to approach this with logic shared across multiple methods? 有没有更好的方法来解决跨多个方法共享的逻辑问题?
You could make this a class method on Finance
: 您可以将此设置为Finance
的类方法:
class Finance
def self.essentials(user)
finance = user.finance
finance.rent.to_i +
finance.mortgage.to_i +
finance.gas.to_i +
finance.groceries.to_i +
finance.carpayment.to_i +
finance.carinsurance.to_i +
finance.othertransit.to_i +
finance.electric.to_i
end
end
I'd put the setup for the instance variables in a before
filter: 我将实例变量的设置放在before
过滤器中:
# controller
before_filter :load_finances, :only => [:index, :spending]
before_filter :load_essentials, :only => [:index, :spending]
def index
end
def spending
end
protected
def load_finances
@finances = Finance.find_all_by_user_id current_user[:id] if current_user
end
def load_essentials
@essentials = Finance.essentials(current_user) if current_user
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.