我遇到的问题是,如果发生验证错误,我视图中的选择框不会保留选定的值。
我有业务和类别关系,它有多对多关联
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
访问控制台中的业务类别。
为了解决我添加的params问题。
<%= @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 hash看起来像这样
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 :(得分:2)
我通过做一些简单的修改来解决这个问题。
在我的控制器中我添加了以下内容
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 }}) %>
答案 1 :(得分:0)
从2019年开始更新,如果您的f.select看起来像这样:
<%= f.select(:sector , options_for_select([["Please select", "Please select"], ["Energy", "Energy"], ["Metals","Metals"], ["Agriculture","Agriculture"], ["Renewables","Renewables"], ["Natural Ressources","Natural Ressources"], ["Other","Other"]])) %>
您要做的就是删除options_for_select(...),如果发生验证错误,页面将“记住”您选择的内容。
<%= f.select(:sector , [["Please select", "Please select"], ["Energy", "Energy"], ["Metals","Metals"], ["Agriculture","Agriculture"], ["Renewables","Renewables"], ["Natural Ressources","Natural Ressources"], ["Other","Other"]]) %>
我不知道这对多选输入如何起作用。我还使用了自己的示例来提高可读性。