在 Rails 中,您的控制器处理传入的 Web 请求。所以如果一个人点击一个链接来创建一条新评论,他们可能会点击如下路线:
http://mysite.com/comments
然后将其路由到CommentsController#create 操作。现在,如果您有很多代码用于创建新评论,那么是的,您应该将其中的一些代码移到 Comment 模型中。否则,如果它非常简单,请不要担心。
一个简单的场景示例:
# POST /comments
def create
@comment = Comment.new(:content => params[:comment_content])
if @comment.save
respond_with @comment
else
# error handling
end
end
如果您需要在创建该注释后运行某个方法,则在 Comment 模型中放置一个回调:
class Comment < ActiveRecord::Base
after_create :do_something
def do_something
# some code here
end
end
如果创建注释更复杂(即,如果控制器中有大量您不想要的代码),则将一些代码移动到 Comment 模型中:
评论控制器
# POST /comments
def create
@comment = Comment.create_comment!(params[:comment_content])
if @comment.errors.any?
# handle errors
else
respond_with @comment
end
end
评论模型
class << self
def create_comment!(comment_content)
comment = Comment.new(:content => comment_content)
# lots of complex comment creation code goes here
return comment
end
end
这使您可以使控制器代码保持简单,同时将更详细的代码移至模型中。