gpt4 book ai didi

ruby-on-rails - Rails 中嵌套资源 View 的最佳实践?

转载 作者:行者123 更新时间:2023-12-04 21:26:29 25 4
gpt4 key购买 nike

我有一个相当简单的模型;用户拥有_许多产品。我希望能够查看所有产品的列表以及与给定用户关联的产品列表。我的路线是这样设置的:

/products
/products/:id
/users
/users/:id
/users/:id/products

这里的问题是我想在 product#index View 和 user/products#index View 中以不同的方式显示产品列表。

有没有“正确”的方法来做到这一点?我当前的解决方案是将产品定义为用户内部的嵌套资源,然后检查 params[:user_id] - 如果找到它,我将呈现一个名为“index_from_user”的模板,否则我只呈现典型的“index”模板。

这是我经常遇到的情况 - 如果有首选的方法来做到这一点,我很想知道......

最佳答案

您可以声明两条“产品”路线 - 一条在用户之下,一条独立于用户,例如:

map .资源:产品
map.resources :users, :has_many => :products

他们都将查找“ProductsController#index”,但第二个将从路由中预先填充“user_id”(注意:“user_id”而不仅仅是“id”)

所以你可以在 index 方法中测试它,并根据它是否存在显示不同的项目。

您需要在 ProductController 中添加一个 before_filter 来实际实例化用户模型,然后才能使用它,例如:

before_filter :get_user # put any exceptions here

def index
@products = @user.present? ? @user.products : Product.all
end

# all the other actions here...


# somewhere near the bottom...
private

def get_user
@user = User.find(params[:user_id])
end

如果你真的想显示完全不同的 View ,你可以在 index 操作中明确地进行,例如:
def index
@products = @user.present? ? @user.products : Product.all
if @user.present?
return render(:action => :user_view) # or whatever...
end
# will render the default template...
end

关于ruby-on-rails - Rails 中嵌套资源 View 的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2464618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com