2012-01-29 91 views
2

假設我有兩個:has_and_belongs_to_many模型通過簡單的索引表連接起來。這是我的routes.rb是什麼樣子:Rails中的RESTful habtm關係

match "foo/:id" => "foos#create", :via => :post 
match "foo/:id" => "foos#update", :via => :put 
match "foo/:id" => "foos#read", :via => :get 
match "foo/:id" => "foos#delete", :via => :delete 

match "foos/:id/bars" => "foos#add_bar", :via => :post 

而最後的路由(一個問題)的方法add_bar映射到其預期酒吧的JSON表示的foo_controller.rb:

def add_bar 
    @bar = Bar.find(params[:bar][:id]) 
    if @bar.nil? 
    @bar = Bar.create(params[:bar]) 
    validation_error(@bar.errors) unless @bar.valid? 
    @bar.save! 
    end 
    @foo.bars << @bar 
    @foo.save! 
    respond(ResponseCode::OK, @bar) 
end 

這有意義嗎?我將匹配推送到rails中的集合的行爲,但從RESTful的角度來看,我感覺很骯髒。也許我錯了。思考?

回答

4

劃痕這一切,用途:

resources :foos do 
    member do 
    post 'bars', :to => "foos#add_bar", :as => :add_bar_to 
    end 
end 

這給你六個基本REST風格的CRUD路線,加上add_bar_to_foo的輔助方法。您的foos控制器應該有show方法而不是read。這是Rails約定。

爲了應對加入吧,

def add_bar 
    @foo = Foo.find(params[:id]) # find the foo 
    @bar = @foo.bars.build(params[:bar]) # build new bar through foo 
    if @bar.save 
    render :json => @bar # 'OK' response 
    else 
    render :json => @bar, :status => :unprocessable_entity # failure response 
    end 
end