Ruby:如果在f.select中选择了“other”,则使用f.select或f.text_field

时间:2012-03-29 22:24:12

标签: ruby-on-rails ruby ruby-on-rails-3

如果在选择表单中选择了“其他”,我需要ruby来从f.select或f.text_field获取值。这怎么可能? 在视图中:

<div class="field">
  Parent</br>
  <% f.label :parent1 %>
  <%= select("jobs","parent1_id",["None","8.5x11","shells"]) %>
  Other:
  <% f.label :parent2 %>
  <%= text_field("jobs","parent2_id") %>
</div>

在控制器中:

def create
  @job = Job.new(params[:job])

    if params[:parent1_id] == "None" #params[:option1_id].nil? #params.has_key?(:option1_id) #Take your pick
        @job.parent = params[:parent2_id]
    else
        @job.parent = params[:parent1_id]
    end

  respond_to do |format|

    if @job.save
      format.html { redirect_to @job, :notice => 'Job was successfully created.' }
      format.json { render :json => @job, :status => :created, :location => @job }
    else
      format.html { render :action => "new" }
      format.json { render :json => @job.errors, :status => :unprocessable_entity }
    end
  end
end

1 个答案:

答案 0 :(得分:0)

解决问题的最简单方法是在select中使用{:include_blank => "none"},并检查控制器中的参数是否为null,如果是,则使用其他参数。


我个人如何使用它:

<%= form_for @thing, :html => { :class => 'form-horizontal' } do |f| %>
  .....
<div class="field">
  <%= f.label :name %><br />
  <%= select_tag "count", "<option>None</option><option>8.5x11</option><option>shells</option>".html_safe %>
</div>
<div class="field">
  <%= f.label :name %><br />
  <%= text_field_tag "users" %>
</div>
  ........
    <div class="form-actions">
      <%= f.submit "Submit", :class => 'btn btn-primary' %>
  .......
    </div>
<% end %>

注意collection_select是select的变体,我在其中传递了另一个模型的项目。

在控制器中:

def create
.......
  if params[:option1_id] == "" #params[:option1_id].nil? #params.has_key?(:option1_id) #Take your pick
    @thing.attribute = params[:option2_id]
  else
    @thing.attribute = params[:option1_id]
  else
end