has_one 到多态关联
我有以下内容:
class Car < ActiveRecord::Base
has_one :driver
end
class Driver < ActiveRecord::Base
belongs_to :car
has_one :license, :as => :licensable
end
class License < ActiveRecord::Base
belongs_to :licensable, :polymorphic => true
end
即,汽车有一名驾驶员,该驾驶员拥有一份许可证(许可证是多态的 - 我们只是在这种情况下说,因为它可以与其他对象关联)。
在routes.rb 中,我有:
resources :cars do
resource :driver do
resource :license
end
end
我想出示我的许可证。路线文件中的“显示”是:
GET /cars/:car_id/driver/license(.:format) {:action=>"show", :controller=>"licenses"}
在我的许可证控制器中,我有:
def show
@license = @licensable.licenses.find(params[:id])
# continues.......
问题是,即使驱动程序与许可证有关系,但由于路线的原因,@licensable 会被认为是汽车。汽车与许可证无关,因此代码不起作用。我想我要么必须改变我的控制器,要么更可能改变我的路线。
I have the following:
class Car < ActiveRecord::Base
has_one :driver
end
class Driver < ActiveRecord::Base
belongs_to :car
has_one :license, :as => :licensable
end
class License < ActiveRecord::Base
belongs_to :licensable, :polymorphic => true
end
i.e., Car has one driver who has one license (license is polymorphic - let's just say in this case since it can be associated with other objects).
In routes.rb I have:
resources :cars do
resource :driver do
resource :license
end
end
I would like to show my license. The "show" in the routes file is:
GET /cars/:car_id/driver/license(.:format) {:action=>"show", :controller=>"licenses"}
In my licenses controller I have:
def show
@license = @licensable.licenses.find(params[:id])
# continues.......
The problem is that even though driver has the relation to license, the @licensable is coming across as Car because of the routes. Car has no relation to license so the code doesn't work. I assume I either have to change my controller or more likely my routes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为从 URL 中您只能获取 car_id,所以这可行:
另一种方法是使用嵌套较少的 REST 接口。如果许可证和汽车都有唯一的 ID,则嵌套并不是真正必要的。
Because from the URL you only get the car_id this could work:
An alternative is to use a less nested REST interface. Nesting is not really necessary if licenses and cars both have unique ID's.