2014-05-10 75 views
2

我試過讓自己擁有和屬於許多關係的工作,遵循Rails指南和我可以在網上找到的所有東西,但他們只是不會出現..當我將我的表單保存到Pin模型中,它不會插入任何關係。如果我通過終端手動添加的關係,像這樣:有多對多的複選框不會節省Rails 4

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

它的工作原理,但它看起來像這樣我的形式(IAM使用Rails 4,所以收藏耶)它不保存的關係(它保存的銷就好)

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 [email protected]? %> 
<%= @pin.minors.each do |minor| %> 
    <%= minor.name %> 
<% end %> 
<% end %> 

<% if [email protected]? %> 
<%= @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權限_pins表仍然是空的,所有幫助和洞察我可以得到!

回答

0

我通過在新方法的引腳控制器中添加@minors = Minor.all來解決這個問題。並用<%= f.collection_check_boxes(:minor_ids, @minors, :id,:name)%>代替<%= collection_check_boxes(:minor_ids, :minor_ids, Minor.all, :id, :name) %>