我有简单的 Rails 应用程序。创建、删除、编辑帖子。我需要评价这篇文章。 将速率函数放置在模型或 Controller 中的何处?为什么?
最佳答案
通常这种事情在两个地方都会发生。您将在模型上有一个 rate
方法,并且在 Controller 中将有一个 rate
操作。
请记住, Controller 的主要功能是接收请求、加载适当的模型、根据需要进行调整并保存结果。通常,模型将实现促进这一点所需的功能。
在 Controller 中你可以做这样的事情:
class ItemsController < ApplicationController
def rate
@item.rate!(session[:user_id], params[:rating])
end
end
在模型中你会有这样的东西:
class Item < ActiveRecord::Base
has_many :ratings
def rate!(user_id, rating)
self.ratings.create(:user_id => user_id, :rating => rating)
end
end
如果没有 Controller ,您就无法访问模型,它必须经过该层,如果没有模型,您就没有持久数据。他们一起工作。
关于ruby-on-rails - 功能定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8313696/