有许多复选框不会保存Rails 4

时间:2014-05-10 17:37:01

标签: checkbox collections ruby-on-rails-4 has-many

我已尝试制作我的并且属于许多工作关系,遵循Rails指南和我在网上可以找到的所有内容,但它们只是不会出现..当我将我的表单只保存到Pin模型时,它没有插入任何关系。如果我通过终端手动添加关系,如下所示:

p = Pin.new
p.minors = [1,2]
p.save

它有效,但我的形状看起来像这样(我使用rails 4,所以收藏yay)它不保存关系(它保存了针很好)

new.html.erb

  <%= collection_check_boxes(:minor_ids, :minor_ids, Minor.all, :id, :name) %>
  <%= collection_check_boxes(:competence_ids, :competence_ids, Competence.all, :id, :name) %>

pinscontroller.rb

class PinsController < ApplicationController

 def create
  @pin = Pin.new(pin_params)
  @pin.user_id = current_user.id

  if @pin.save
    redirect_to pin_path(@pin)
  end
 end

def new
 @pin = Pin.new()
end

def show
 @pin = Pin.find(params[:id])
end


private
def pin_params
 params.require(:pin).permit(:title, :name, :url, { :minor_ids => [] }, { :competence_ids => [] },)
end

和我的模特 Pin.rb

 class Pin < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :minors
has_and_belongs_to_many :competences
 end

Minor.rb

 class Minor < ActiveRecord::Base
has_and_belongs_to_many :pins
 end

Competence.rb

 class Competence < ActiveRecord::Base
  has_and_belongs_to_many :pins
 end

销/ show.html.erb

这是我尝试检查关系是否通过的方式。除了我通过控制台做的那些之外,它们都是空的和0。

<%=  @pin.minors.count.inspect %>
<%=  @pin.competences.count.inspect %>

<% if !@pin.minors.empty? %>
<%= @pin.minors.each do |minor| %>
  <%= minor.name %>
<% end %>
<% end %>

<% if !@pin.competences.empty? %>
<%= @pin.competences.each do |comp| %>
  <%= comp.name %>
<% end %>
<% end %>

Schema.rb

create_table "competences", force: true do |t|
 t.string   "name"
 t.datetime "created_at"
 t.datetime "updated_at"
 t.integer  "pin_id"
end

create_table "competences_pins", force: true do |t|
 t.integer  "pin_id"
 t.integer  "competence_id"
 t.datetime "created_at"
 t.datetime "updated_at"
end

create_table "minors", force: true do |t|
 t.string   "name"
 t.datetime "created_at"
 t.datetime "updated_at"
 t.integer  "pin_id"
end

create_table "minors_pins", force: true do |t|
 t.integer  "pin_id"
 t.integer  "minor_id"
 t.datetime "created_at"
 t.datetime "updated_at"
end

create_table "pins", force: true do |t|
 t.string   "title"
 t.string   "url"
 t.string   "image"
 t.string   "username"
 t.integer  "views"
 t.datetime "created_at"
 t.datetime "updated_at"
 t.integer  "user_id"
end

那么,我错过了一步吗?到目前为止,除了 minors_pins compes_pins 表之外,我已经尝试了所有内容,我可以得到所有的帮助和见解!

1 个答案:

答案 0 :(得分:0)

我通过在新方法的引脚控制器中添加@minors = Minor.all来修复此问题。并将<%= collection_check_boxes(:minor_ids, :minor_ids, Minor.all, :id, :name) %>替换为<%= f.collection_check_boxes(:minor_ids, @minors, :id,:name)%>