2014-02-22 31 views
1

我在创建新Post时调用的Rails应用程序控制器中有一个方法。我也创建了一个API来创建一个新的Post。但是,似乎我需要在我的API BaseController中为我的应用程序控制器方法重复代码。在我的Rails应用程序中放置应用程序控制器方法的最佳位置在哪里,以便我不必重复API的代码?有没有一种API基础控制器可以从ApplicationController继承的方法?Rails API - 保持应用程序控制器方法DRY

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 
+0

hm,不确定但也许你可以把它们放在应用程序控制器中? – user273072545345

+0

我目前在应用程序控制器中有方法,但除非我重复基本控制器中的代码,否则我会得到一个'NoMethodError(undefined method)' – diasks2

+1

,看起来像'foo_action'应该是模型的一部分。很难跟你说出所有的相关信息 – phoet

回答

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 
相关问题