在rails中保存数据库中的复选框值

时间:2014-01-01 17:23:39

标签: ruby-on-rails

我有一个这样的表格

 <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <% counter = 1 %>
    <% @semester.each do |semester|  %>
        <% checkboxs = "subchecked" + counter.to_s %>
        <%= check_box_tag(checkboxs, semester.id) %>
        <%= label_tag(checkboxs, semester.name) %>
        <% counter = counter + 1 %>
    <% end %>
  </div>

并且在我的创建动作中,我尝试了类似这样的事情

def create
    @subject = Subject.new(params[:subject])

         sem =  params[:checkboxs]
    name = params[:name]       
    counter = 0

    respond_to do |format|
      if @subject.save

        sem.each do |sem|              
          sem.update_attributes!(:name => name, :semester_id => sem[counter])
          counter = counter + 1
        end

        format.html { redirect_to @subject, notice: 'Subject was successfully created.' }
        format.json { render json: @subject, status: :created, location: @subject }
      else
        format.html { render action: "new" }
        format.json { render json: @subject.errors, status: :unprocessable_entity }
      end
    end
  end

但这没有值,而是显示错误

undefined method `each' for nil:NilClass

My new action
      def new
        @subject = Subject.new
        @semester = Semester.all
        respond_to do |format|
          format.html # new.html.erb
          format.json { render json: @subject }
        end
      end

1 个答案:

答案 0 :(得分:0)

您应该检查帖子中的数据。您的帖子值似乎不是“复选框”,而是“subchecked1”...“subcheckedN”。这可能是失败的原因。

更改

<% checkboxs = "subchecked" + counter.to_s %>

<% checkboxs = "subchecked[#{counter.to_s}]" %>

sem =  params[:checkboxs]

sem =  params[:subchecked]