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的角度來看,我感覺很骯髒。也許我錯了。思考?