【问题标题】:rails restful select_tag with :on_changerails restful select_tag with :on_change
【发布时间】:2011-02-06 07:18:49
【问题描述】:

所以我终于开始在rails中使用rest了。

我希望使用产品类别以及选择其中一个类别时,我希望它更新更改产品。

我以前用过这个

<% form_for :category, :url => { :action => "show" } do |f| %>
<%= select_tag :id, options_from_collection_for_select(Category.find(:all), :id, :name),
{ :onchange => "this.form.submit();"} %>
<% end %>

但是现在它不起作用,因为它试图执行显示操作。

我有两个控制器 1) 产品 2) product_categories

products belongs_to product_categories with a has_many

我该怎么做。

由于产品列在 products 控制器和 index 操作中,我应该使用 products 控制器还是应该使用 product_categories 控制器来查找类别,例如在 show 操作中,然后呈现产品/索引页面。

但我遇到的真正问题是如何获得此表单或任何其他选项来使用宁静的路线。

【问题讨论】:

    标签: ruby-on-rails rest


    【解决方案1】:

    第一条路线 - 您需要将产品定义为资源,因此您将拥有辅助方法:edit_product_path(@product)new_product_path 等等:

    # routes.rb
    map.resource :products
    

    然后控制器 - 标准资源控制器:

    # products_controller.rb
    def edit
      @product = Product.find(params[:id])
    end
    
    def update
      @product = Product.find(params[:id])
      if @product.update_attributes(params[:product])
        flash[:notice] = "Product updated"
        redirect_to @product
      else
        render :edit
      end
    end
    

    现在查看 - 用户 form_for 可以更轻松地为特定对象(新的或现有的)构建表单。对于新对象,默认情况下它指向此资源的控制器上的#create 操作,而现有指向#update。如果需要,您可以随时覆盖此路径:

    # products/new.html.erb
    <% form_for @product do |f| %>
      <%= f.select :product_category, Category.all, {}, {:onchange => "this.form.submit();" %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多