【问题标题】:Rails update and create taskRails 更新和创建任务
【发布时间】:2011-12-05 02:38:04
【问题描述】:

在更新或创建时在 Rails 中,如果我需要运行另一种方法,这就是我一直在为我的应用程序做的事情。(位于我的控制器中)

def create
  # Perform stuff
end

def update
  # Perform stuff
end

这方面的东西看起来真的是被黑掉了,一定有比我现在更专业的方法来做这件事。有什么方法我需要设置我的模型以便在创建或更新模型时运行任务。

【问题讨论】:

  • 这个问题没有任何意义。 createupdate 是标准控制器操作。我不明白它是如何“被黑掉”的。

标签: ruby-on-rails model-view-controller methods model


【解决方案1】:

在 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

这使您可以使控制器代码保持简单,同时将更详细的代码移至模型中。

【讨论】:

    【解决方案2】:

    ActiveRecord callbacks怎么样?

    它们贯穿于模型的整个生命周期,可用于在您关心的事情发生时执行任务 - 例如正在创建或更新模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多