简体   繁体   English

嵌套路由,通过关联查询

[英]Nested routes, querying through association

I have the following model structure: 我具有以下模型结构:

USER
has_many :items
has_many :payments

ITEM
belongs_to :user
has_many :payments

PAYMENT
belongs_to user
belongs_to listing

So one USER can be the creator of PAYMENT and another can have the access to that same PAYMENT , but as a receiver of the payment (through the item he owns) 因此,一个用户可以是PAYMENT的创建者,而另一个用户可以访问同一PAYMENT ,但是作为付款的接收者(通过他拥有的商品)

How do you organize the routes and controller here to distinguish between the two and to query the model in a clean manner? 您如何在此处组织路径和控制器以区分两者并以简洁的方式查询模型?

I tried nesting routes to achieve the full RESTFUL routing: 我尝试嵌套路由以实现完整的RESTFUL路由:

/items/x/payment/y

...but I gained nothing... I always end up invoking the same method on the same controller where I have to get user's PAYMENTS and all PAYMENTS for user's items. ...但是我一无所获...我总是最终在同一控制器上调用相同的方法,在该控制器上,我必须获取用户的付款以及用户物品的所有付款。 Also, I read a great article that nesting shouldn't be deeper than 1 level and the truth is that I don't really care about whether I get to show payment 3 using /payment/3 or the longer version. 另外,我读了一篇很棒的文章,说嵌套不应该深于1级,事实是我并不真正在乎是否显示使用/payment/3或更长版本的/payment/3

What I care about is keeping my code base maintainable :) I am new to RoR, but what I got clear is that things in Rails always have nice solutions :p 我关心的是保持代码库的可维护性:)我对RoR还是陌生的,但是我清楚的是,Rails中的东西总是有不错的解决方案:p

What I have at the moment is: ItemsController#show where I call Payment.as_payer(current_user) and Payment.as_payer(current_user) and in Booking model implemented these two methods that return all payments that user created or received through items... 目前我所拥有的是: ItemsController#show我在其中调用Payment.as_payer(current_user)Payment.as_payer(current_user)并且在Booking模型中实现了这两种方法,它们返回用户通过项目创建或接收的所有付款...

Any suggestion regarding the architecture is welcome :) Routes, Controllers, Model, scopes... 任何有关体系结构的建议都欢迎:)路由,控制器,模型,范围...

Try only showing your current user's payments by doing the following in your view. 通过在视图中执行以下操作,尝试仅显示当前用户的付款。

<% @user.payments.each do |payments| %>

To get the user's item's payments: 要获取用户商品的付款,请执行以下操作:

<% @user.items.each do |item|  %>
    <% item.payments each do |payment|  %>
    ....your view code...
    <% end %>
<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM