has_one 到多态关联

发布于 2024-10-23 20:17:24 字数 876 浏览 5 评论 0原文

我有以下内容:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

任性一次 2024-10-30 20:17:24

因为从 URL 中您只能获取 car_id,所以这可行:

@car = Car.find(params[:car_id])
@license = @car.driver.licensable

另一种方法是使用嵌套较少的 REST 接口。如果许可证和汽车都有唯一的 ID,则嵌套并不是真正必要的。

Because from the URL you only get the car_id this could work:

@car = Car.find(params[:car_id])
@license = @car.driver.licensable

An alternative is to use a less nested REST interface. Nesting is not really necessary if licenses and cars both have unique ID's.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文