2

我遇到的问题是,如果发生验证错误,我的视图中的选择框不会保留选择的值。

我有具有多对多关联的业务和类别关系

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.categorieswhich 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

结尾

4

2 回答 2

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 }}) %>
于 2012-12-05T04:15:42.677 回答
-1

从 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"]]) %>

我不知道这如何与多选输入一起使用。为了提高可读性,我还使用了自己的示例。

于 2019-01-31T13:36:42.437 回答