[rails创建页面从

问题描述 投票:-1回答:2

我有CategoriesProducts。产品有关系belongs_to :category

在类别显示页面中,我有一个按钮来添加新产品。此按钮转到我创建新产品的页面,但是我需要为新产品指定类别。

如何将id页面从原来的位置传递给新产品?因此,如果我在类别category中,则单击“添加产品”,并且该产品自动与Electronic类别相关联。

希望你能理解我想要的。谢谢

ruby-on-rails ruby-on-rails-3.2
2个回答
0
投票

首先,我要确定每个产品是否包含在]中>>一个类别,或者它是否仅与一个类别相关联。它包含的提示是:

  • 您希望每个产品都有一个'父'类别。
  • 您希望每个产品都将始终出现在其父类别的上下文中。
  • [并且仅当您认为是这种情况时,我才会尝试嵌套

该类别中的产品资源。
Eletronic

如果您这样做,rails将确保您的产品与正确的类别相关联。魔术发生在# routes.rb resources :categories do resources :products end # products_controller.rb (SIMPLIFIED!) class ProductController < ApplicationController before_filter :get_category def new @product = @category.products.build end def create @product = @category.products.build(params[:product]) if @product.save redirect_to @product else render template: "new" end end def get_category @category = Category.find(params[:category_id]) end end 中,它会根据关系自动设置category_id。

[如果您希望将类别和产品保留为简单的关联,虽然我很想以稍微不同的方式来处理它,但我只会按照Eric Andres的回答使用查询参数:

@category.products.build

这主要只是风格上的差异。埃里克(Eric)的答案也适用-我只是更愿意在模型本身上设置值,而不用担心参数等问题。


1
投票

您需要在链接中传递# link: new_product_path(category_id: @category.id) # So far, so similar. # products_controller.rb class ProductsController < ApplicationController def new @product = Product.new @product.category_id = params[:category_id].to_i if params[:category_id] end end # new.erb <%= f.hidden_field :category_id %> ,例如category_id

© www.soinside.com 2019 - 2024. All rights reserved.