为什么check_box值没有发布到db

时间:2014-09-18 02:21:53

标签: ruby-on-rails ruby-on-rails-4

当我提交下面的表格时,“已发布”的check_box值未发布。

  

params3 = {“utf8”=>“✓”,   “authenticity_token”=> “中i4SbblLJKIwba9yD30sDQCsir28 / xdUxQZ90qYTNn0A =”,   “story”=> {“name”=>“asdsaddsad”,“post”=>“asdasdasdasd”,   “user_id”=>“13”,“image_id”=>“1”,“已发布”=>“1”},“提交”=>“保存   故事“,”动作“=>”创建“,”控制器“=>”故事“}

def create
    @story = Story.new(story_params)

    respond_to do |format|
      if @story.save
        format.html { redirect_to @story, notice: 'Story was successfully created.' }
        format.json { render action: 'show', status: :created, location: @story }
      else
        format.html { render action: 'new' }
        format.json { render json: @story.errors, status: :unprocessable_entity }
      end
    end
  end

<%= form_for @story do |f| %>
        <%= f.text_field :name, placeholder: "Enter Title" %>
        <%= f.text_area :post, placeholder: "Enter Story" %>
        <br/>
        <%= f.hidden_field :user_id, value: current_user.id %>
        <%= f.hidden_field :image_id, value: @image.id %>
        <%= f.label "Publish this" %>
        <%= f.check_box :published %>
        <%= f.submit "Save Story" %>
    <% end %> 

1 个答案:

答案 0 :(得分:1)

传递给操作的数据是story,如params3哈希中所示。此外,正在发布published复选框。默认情况下,复选框会传递10来表示true / false。 Rails会相应地更新值,并接受10作为复选框的值:

params3 = {"utf8"=>"✓", "authenticity_token"=>"i4SbblLJKIwba9yD30sDQCsir28/xdUxQZ90qYTNn0A=",  "**story**"=>{"name"=>"asdsaddsad", "post"=>"asdasdasdasd", "user_id"=>"13", "image_id"=>"1", "published"=>"1"}, "commit"=>"Save Story", "action"=>"create", "controller"=>"stories"}

因此,您的对象创建将需要使用这些参数。由于您使用的是Rails 4,因此您需要使用strong_parameters。您需要验证published是否为params散列中的允许值。

def story_params
  params.require(:story).permit(...., :published, ...)
end