2012-11-08 25 views
0

我的问题是我的视图中的选择框不保持选择的值,如果发生验证错误。当验证错误发生时,选择框不保留参数值 - Rails 3

我有具有多对多关联

category.rb

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :businesses 

business.rb

class Business < ActiveRecord::Base 
    has_and_belongs_to_many :categories 

在我看来,我有一个选择栏的业务和种类对应

<%= f.select(:category_tokens, Category.all.collect {|c| [ c.name, c.id ] }, { :include_blank => "Select Category", :selected => params['category'] }}) %> 

我可以使用business.categories返回和数组访问控制台中的业务类别。

在我看来解决我添加的参数。

<%= @business.categories %> 
<%= @business.attributes.inspect %> 
<%= @business.user.attributes.inspect %> 

这些显示输出提供了以下

[#<Category id: 2, name: "kitchen renovations", created_at: "2012-10-19 14:16:52", updated_at: "2012-10-19 14:16:52">] 

{"id"=>nil, "business_name"=>"", ... additional attributes} 

{"id"=>nil, "email"=>"", ... additional attributes} 

params哈希表看起来像这样

Processing by BusinessesController#create as HTML 
Parameters: {"utf8"=>"✓", 
"authenticity_token"=>"fVz1mJZI8QT/HYKRph8YTvzRec0IVV0RS55v5QD5SL0=", 
"business"=>{"category_tokens"=>"2", 
"location"=>"", "service_area"=>"20", 
"business_name"=>"", "abn_number"=>"", 
"business_description"=>"", 
"address"=>"", "suburb"=>"", 
"notification_type"=>"", 
"user_attributes"=>{"first_name"=>"", "phone"=>"", "email"=>"", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}, "commit"=>"Sign up my Business"} 

那么类别被设定,但我不知道怎么加这对我在视图中的选择来在出现验证错误时使用该类别作为选择值。

编辑 - 添加控制器代码----

class BusinessesController < ApplicationController 

    def new 
    @business = Business.new 
    @business.build_user 
    end 

    def create 
    @business = Business.new(params[:business]) 
    respond_to do |format| 
     if @business.save 
     cookies[:auth_token] = @business.user.auth_token 
     format.html { redirect_to jobs_users_path, notice: 'Your business was successfully created.' } 
    else 
    format.html { render action: "new" } 
    end 
end 

+0

您可以提供控制器操作,将提交发送给? –

+0

@CarsonCole,我已经添加了控制器代码。 –

回答

1

我通过制作一些简单的改变解决了这个问题。

在我的控制器添加以下

def create 
    #... 
    category = (params[:business][:category_tokens]) 
    @category = category 
    #... 
end 

然后在我所选择的选项视图中使用这一点。

<%= f.select(:category_tokens, Category.all.collect {|c| [ c.name, c.id ] }, { :include_blank => "Select Category", :selected => @category }}) %>