【发布时间】:2017-04-29 18:41:46
【问题描述】:
我有很多具有高级关系的资源(habtm/hm/hmt 等),你能想象到的一切,但现在是时候为这个 API 编写一个漂亮的路由了。 问题是,我无法找到关于嵌套资源 + 高级关系的最佳实践来做我的路由,这就是我想要做的:
这是我与相关关系的模型
# app/models/candidate.rb
class Candidate < ApplicationRecord
include Sociable, Locatable
belongs_to :user
has_many :sourcing_accounts
has_many :accounts, through: :sourcing_accounts
has_many :users, through: :sourcing_accounts
end
# app/models/sourcing_account.rb
class SourcingAccount < ApplicationRecord
belongs_to :account
belongs_to :candidate
belongs_to :user
end
# app/models/user.rb
class User < ApplicationRecord
include Sociable
has_many :candidates
has_many :campaigns
has_many :sourcing_account
end
对于这个例子,我愿意通过创建SourcingAccount 来创建Candidate 和User 之间的关系。
resources :candidates do
resources :accounts
resources :users, only: [:index] do
post :remove
post :add
end
end
它生成:
v1_candidate_user_remove POST /v1/candidates/:candidate_id/users/:user_id/remove(.:format) api/v1/users#remove {:subdomain=>"api", :format=>:json}
v1_candidate_user_add POST /v1/candidates/:candidate_id/users/:user_id/add(.:format) api/v1/users#add {:subdomain=>"api", :format=>:json}
我没有发现任何关于此的信息。有最佳实践吗??? 如果不是,您认为最适合这种情况的是什么?
如果没有精确性,Rails 想将其路由到 users#remove 和 users#add,我认为这是完全错误的。这些动作不能属于用户控制器。
奖金:
创建属于其他 2 个模型的 Account 的多态路径应该是什么(具有存在验证),2 个模型是 Source,另一个是多态 [Candidate,User] # for example,(它们是 Sociable 模型)
【问题讨论】:
标签: ruby-on-rails ruby routing ruby-on-rails-5