我遇到的问题是,如果发生验证错误,我的视图中的选择框不会保留选择的值。
我有具有多对多关联的业务和类别关系
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
which return 和 array 访问控制台中的业务类别。
在我看来,要对我添加的参数进行故障排除。
<%= @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}
参数哈希看起来像这样
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
结尾