我有两个型号的客户和PriceGroup。客户模型包含名为price_group_id的字段。PriceGroup模型有:id字段和:name字段。
我向客户控制器添加了一个名为add_price_group的新操作。当客户已经创建时,我需要为他添加一个PriceGroup。
我使用了form_for和select助手。
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的新手,无法理解如何在一起使用所有这些代码。需要帮助!
发布于 2015-07-24 05:49:25
在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包含在params中,而您的控制器将将其保存在客户中。
希望这能有所帮助。
发布于 2015-07-24 06:38:53
我修好了!在……里面
<%= form_for @customer, url: {action: "add_price_group"}, html: {class: "form-inline"} do |f| %>正确是
<%= form_for @customer, html: {class: "form-inline"} do |f| %>https://stackoverflow.com/questions/31602735
复制相似问题