Rails 中的 RESTful habtm 关系
假设我有两个 :has_and_belongs_to_many
模型,它们通过一个简单的索引表连接起来。这就是我的routes.rb的样子:
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
最后一条路线(有问题的路线)映射到foo_controller.rb中的add_bar
方法,该方法需要一个bar的JSON表示:
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 的角度来看,这对我来说感觉很脏。也许我错了。想法?
So let's say I have two :has_and_belongs_to_many
models that are joined by a simple index table. This is what my routes.rb looks like:
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
And the last route (the one in question) maps to a the add_bar
method in the foo_controller.rb which expects a JSON representation of a bar:
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
Does this make sense? I'm matching the behavior of pushing to the collections in rails, but it feels dirty to me from a RESTful standpoint. Maybe I'm wrong. Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
重新开始并使用:
这为您提供了六个基本的 RESTful CRUD 路由,以及一个
add_bar_to_foo
辅助方法。您的 foos 控制器应该有一个show
方法,而不是read
。这是 Rails 约定。要处理添加条形,
Scratch all of that and use:
This gives you the six basic RESTful CRUD routes, plus an
add_bar_to_foo
helper method. Your foos controller should have ashow
method instead ofread
. This is Rails convention.To handle adding bars,