2012-11-08 58 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 }}) %>