复选框未存储在数据库中

时间:2015-11-25 10:25:00

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

section_controller:

def save
    @section =Section.new(require_section)
    @section.user_id = @level.id
    if @section.save
        flash[:notic]='post created'
        redirect_to :action=>'index'
    else
        render :action=>'create'
    end

end

def update

@section= Section.find(params[:id])
  if @section.update_attributes(require_section)
  flash[:notic]='post updated'
  redirect_to :controller=>'admin',:action=>'index'
  else
  render 'edit'
end
private

    def require_section
        params.require(:section).permit(:title, :tag, :visible, :content,:short_content,:teaser,:category_ids)
    end

create.html.erb:

<%= form_for :section,:url=>{:action=>'save'} do |f| %>

Title:<%= f.text_field :title ,:class=>'form-control'%>
.
.
.
 <% Category.all.each do |cat| %>


<%= check_box_tag :category_ids,cat.id %>
<%= cat.name %>
<% end %>
<%= submit_tag 'submit',:class=>'btn btn-success'%>
<% end %>
</div>

模型:

class Categorization < ActiveRecord::Base
belongs_to :category
belongs_to :section

end

class Category < ActiveRecord::Base
has_many :categorizations
has_many :sections, :through => :categorizations
end

has_many :categorizations
has_many :categories,:through => :categorizations

提交表单类别未存储在数据库中但发布成功后

我检查了数据库,category_ids列有空字符串

我也会跟进此tutorial

Rails:4 数据库:postgresql

2 个答案:

答案 0 :(得分:3)

您的复选框标记应为:

<%= check_box_tag "section[category_ids]", cat.id %>

答案 1 :(得分:1)

试试这个: -

<% Category.all.each do |cat| %>
    <%= check_box_tag "section[category_ids][]", cat.id %>
    <%= cat.name %>
<% end %>