我正在为我的rails应用程序进行重构。我读过许多关于将控制器逻辑移动到模型的文章,但我尝试时遇到了一些问题。
我需要帮助
由于我还没有为我的应用程序进行任何重大重构,所以首先尝试了一个简单的重构。
PostsController(前)
def create
@post = Post.create(params[:post])
@post.user_id = session[:user_id]
@post.num_likes = 0
@post.num_dislikes = 0
@geoip = GeoIP.new("#{Rails.root.to_s}/db/GeoIP.dat").country(request.remote_ip)
@post.user_location = @geoip.country_name
endPostModel(新)
before_save :initialize_post
def initialize_post
self.user_id = session[:user_id]
self.num_likes = 0
self.num_dislikes = 0
@geoip = GeoIP.new("#{Rails.root.to_s}/db/GeoIP.dat").country(request.remote_ip)
self.user_location = @geoip.country_name
endPostsController(新)
def create
@post = Post.create(params[:post])
end但是,由于session undefined和method request undefined这样的错误,我甚至没有完成这个简单的重构。我不知道为什么不能在模型类中使用这些操作。
有人能解释一下背后的原因吗?能告诉我一些好的文档来帮助我顺利地完成重构过程吗?
非常感谢。
发布于 2013-01-07 10:26:39
为了你的控制器我会做一些类似..。
def create
@post = Post.new(params[:post])
@post.user_id = session[:user_id]
@post.ip_address = request.remote_ip
@post.save
end还有你的模特..。类似的东西;
attr_accessor :ip_address
before_create :set_default_values
before_save :geo_locate
private
def geo_locate
@geoip = GeoIP.new("#{Rails.root.to_s}/db/GeoIP.dat").country(self.ip_address) rescue nil
self.user_location = @geoip.country_name unless @geoip.blank?
end
# This only runs when a new record is created. Alternatively, look into setting a default value on your database columns!
def set_default_values
self.num_likes = 0
self.num_dislikes = 0
end发布于 2013-01-07 07:11:13
您不能将控制器中的所有代码移动到模型中。一些代码,如会话处理和请求,仅限于控制器。它们在模型内部不可用。只有仅限于模型级处理的处理代码才需要在模型中。
以下是重构rails代码的最佳书籍,
http://www.amazon.com/Rails-AntiPatterns-Refactoring-Addison-Wesley-Professional/dp/0321604814
https://stackoverflow.com/questions/14191328
复制相似问题