2014-02-22 30 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 
相關問題