【问题标题】:rails create page fromrails 创建页面
【发布时间】:2013-05-30 19:11:59
【问题描述】:

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

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

如何将id 从我所在的category 页面传递到新产品?因此,如果我属于 Electronic 类别,我点击“添加产品”,该产品将自动与 Eletronic 类别相关联。

希望你能明白我想要什么。 谢谢

【问题讨论】:

  • 您需要展示一些尝试自己寻找答案的尝试,然后寻求帮助,而不是仅仅要求其他人为您找到答案。
  • 问题是我已经试图找到如何做到这一点,但我没有找到我真正想要的。

标签: ruby-on-rails ruby-on-rails-3.2


【解决方案1】:

您需要在链接中传递category_id,例如new_product_path(category_id: @category.id)

您还需要在产品表单中有一个字段来保存类别的 ID,例如 <%= f.hidden_field :category_id, params[:category_id] %>

【讨论】:

  • 谢谢,这真的很有帮助。我不知道 hidden_​​field,我不得不更改为 link_to。我使用的是 button_to。
【解决方案2】:

首先,我会决定每个产品是否包含在一个类别中,或者它是否只是与一个类别相关联。它包含的提示是:

  • 您希望每个产品都只有一个“父”类别。
  • 您希望每个产品始终出现在其父类别的上下文中。

当且仅当您认为是这种情况时,我会很想嵌套该类别中的产品资源。

# 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

如果您这样做,rails 将确保您的产品与正确的类别相关联。奇迹发生在@category.products.build,它会根据关系自动设置category_id。

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

# 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 %>

这主要只是风格上的差异。 Eric 的回答也可以——我只是更喜欢在模型本身上设置值,而不是让视图担心参数等。

【讨论】:

  • 感谢您的精彩解释。我不会使用嵌套元素,因为我是 rails 的新手,但我知道 rails 可以做什么。
猜你喜欢
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 2013-01-29
  • 2012-05-09
  • 1970-01-01
相关资源
最近更新 更多