如何使用form_for helper

时间:2015-07-24 05:19:54

标签: ruby-on-rails ruby ruby-on-rails-4

我有两个型号Customer和PriceGroup。客户模型包含名为price_group_id的字段。 PriceGroup模型具有:id字段和:名称归档。

我向客户控制器添加了一个名为add_price_group的新操作。当客户已经创建时,我需要为他添加PriceGroup。

我使用了form_forselect帮助器。

show.html.erb列表:

<%= form_for @customer, url: {action: "add_price_group"}, html: {class: "form-inline"} do |f| %>
        <div class="form-group">
          <table class="table table-hover table-condensed table-bordered">
            <% @customer.price_group.present? ? @row_color = "success" : @row_color = "danger" %>
            <tr class = <%= @row_color %>>
              <td><strong>Current price group</strong></td>
              <td><%= @customer.price_group.present? ? @customer.price_group.name : "Not set!"%></td>
            </tr>
          </table>
          <label>Choose new price group</label>
          <%= select("price_group", "id", PriceGroup.all.collect {|p| [ p.name, p.id ] }, {}, {class: "form-control"}) %>
          <p style="margin-top:10px;"><%= f.submit "Add price group to customer", class: "btn btn-primary btn-xs" %></p>
        </div>
    <% end %>

customers_controller.rb列表:

class CustomersController < ApplicationController
    def new
        @customer = Customer.new
    end

    def create
        @customer = Customer.create(customer_params)
        if @customer.errors.empty?
            redirect_to @customer
        else
            render "new"
        end
    end

    def show
        @customer = Customer.find(params[:id])
    end

    def edit
        @customer = Customer.find(params[:id])
    end

    def update
        @customer = Customer.find(params[:id])
        @customer.update_attributes(customer_params)
        if @customer.errors.empty?
            redirect_to @customer
        else
            render "edit"
        end 
    end

    def index
        @customers = Customer.all
    end

    def destroy
        @customer = Customer.find(params[:id])
        @customer.destroy
        redirect_to customers_path
    end

    def add_price_group
        @customer.update_attributes(customer_params)
    end

    private
        def customer_params
            params.require(:customer).permit(:customer_type_id, :price_group_id, :name, :short_name, :phone) 
        end
end

在routes.rb中:

resources :customers do
    post :add_price_group, :on => :collection
  end
  resources :price_groups

我只需更新客户模型中的price_group_id字段。

我是Rails的新手,无法理解如何将所有这些代码一起使用。需要帮忙!

2 个答案:

答案 0 :(得分:0)

在你所拥有的form

<%= select("price_group", "id", PriceGroup.all.collect {|p| [ p.name, p.id ] }, {}, {class: "form-control"}) %>

将其更改为此并尝试:

<%= f.collection_select(:price_group_id, PriceGroup.all, :id, :name, { :class=>'form-control' }) %>

它会自动在参数中包含选定的price_group_id,您的控制器会将其保存在客户中。

希望这有帮助。

答案 1 :(得分:0)

我修好了!在

<%= form_for @customer, url: {action: "add_price_group"}, html: {class: "form-inline"} do |f| %>

正确

<%= form_for @customer, html: {class: "form-inline"} do |f| %>