我在我的Rails应用程序控制器中有一个方法,我在创建新帖子时调用该方法。我还创建了一个API来创建一个新帖子。但是,似乎我需要在我的API BaseController中重复我的应用程序控制器方法的代码。在我的Rails应用程序中放置应用程序控制器方法的最佳位置在哪里,以便我不必重复API的代码? API基本控制器是否可以从ApplicationController继承?
Rails app
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
答案 0 :(得分:1)
基于@ 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