The problem I have is the select box in my view does not maintain the value selected if a validation error occurs.
I have business and category relationship which has a many to many association
category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :businesses
business.rb
class Business < ActiveRecord::Base
has_and_belongs_to_many :categories
In my view I have a select field
<%= f.select(:category_tokens, Category.all.collect {|c| [ c.name, c.id ] }, { :include_blank => "Select Category", :selected => params['category'] }}) %>
I can access the business categories in the console using business.categories which returns and array.
In my view to troubleshoot the params I’ve added.
<%= @business.categories %>
<%= @business.attributes.inspect %>
<%= @business.user.attributes.inspect %>
The output for these shows provides the following
[#<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}
The params hash looks like this
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"}
So the category is being set but I’m not sure how to add this to my select in the view to use the category as the select value when a validation error occurs.
EDIT — adding controller code —-
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
end
I fixed this issue by making a few simple changes.
in my controller I added the following
Then used this in my view for the selected option.