【问题标题】:Rails API - keeping an application controller method DRYRails API - 保持应用程序控制器方法 DRY
【发布时间】:2014-02-22 03:16:50
【问题描述】:

我的 Rails 应用程序控制器中有一个方法,我在创建新帖子时调用它。我还创建了一个 API 来创建一个新帖子。但是,似乎我需要在我的 API BaseController 中重复我的应用程序控制器方法的代码。将应用程序控制器方法放在我的 Rails 应用程序中的最佳位置在哪里,这样我就不必重复 API 的代码? API基控制器是否可以从ApplicationController继承?

Rails 应用程序

class PostsController < ApplicationController
  def create
    @post = Post.new(post_params)
    @post.text = foo_action(@post.text)
    if @post.save
      redirect_to posts_path
    else
      render :new
    end
  end
end

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def foo_action(string)
    return string
  end
end

Rails API

class Api::V1::PostsController < Api::V1::BaseController
  def create
    @post = Post.new(post_params)
    @post.text = foo_action(@post.text)
    if @post.save
      respond_with(@post)
    end
  end
end

class Api::V1::BaseController < ActionController::Base
  respond_to :json

  def foo_action(string)
    return string
  end
end

【问题讨论】:

  • 嗯,不确定这个但也许你可以把它们放在应用程序控制器中?
  • 我目前在应用程序控制器中有该方法,但除非我在基本控制器中重复代码,否则我会得到一个NoMethodError (undefined method)
  • 看起来 foo_action 应该是模型的一部分。很难说你把所有相关信息都删掉了
  • @diasks2,好吧,就像我说的,不确定(主要是因为我是新人),但也许您可以将其称为辅助方法?这样,您可以在 Rails API 中调用它而无需重复?
  • 谢谢@phoet,这是我正在寻找的指导。

标签: ruby-on-rails inheritance ruby-on-rails-4


【解决方案1】:

根据上面cmets中@phoet的推荐,我将foo_action方法移到了Post模型中:

class Post < ActiveRecord::Base
  def foo_action
    string = self.text
    return string
  end
end

class PostsController < ApplicationController
  def create
    @post = Post.new(post_params)
    @post.text = @post.foo_action
    if @post.save
      redirect_to posts_path
    else
     render :new
    end
  end
end

class Api::V1::PostsController < Api::V1::BaseController
  def create
   @post = Post.new(post_params)
   @post.text = @post.foo_action
   if @post.save
     respond_with(@post)
   end
 end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多