2017-05-30 46 views
0

我有兩個型號industry_matcher和IndustryMatcherRubyonRails無法保存的has_many關係

class IndustryMatcher < ActiveRecord::Base  
    has_many :industries, class_name: 'Staffroom', conditions: ["staffroom_type = 'Industry'"] 

型號教工休息室

class Staffroom < ActiveRecord::Base 
    has_many :industry_matchers 

現在我已經創建了一個ActiveAdmin資源,這基本上是staffroom

型號這需要在名稱和形式是行業用戶可以從select2字段中選擇。

ActiveAdmin.register IndustryMatcher do 
    config.sort_order = 'name_asc' 
    menu :parent => 'Job Networks', :label => 'Industry Matcher' 


    form do |f| 
    f.semantic_errors *f.object.errors.keys 
    f.inputs 'Industry' do 
     f.input :name 
     f.input :industries, :include_blank => false, :as => :select, :multiple => true, :input_html => {class: "chzn-select"}, collection: Staffroom.industry 
     end 
     f.actions 
    end 

end 

我可以保存模型IndustryMatcher的數據,但關係根本不會保存。

這是連接兩個

class IndustryMatcherStaffroom < ActiveRecord::Base 
    attr_accessible :industry_id, :staffroom_id 

    belongs_to :industry_matcher 
    belongs_to :staffroom 
end 

我會很感激,如果有人能告訴我什麼,我在這裏失蹤,爲什麼關係沒有得到保存的模型類。

保存記錄,當我嘗試對其進行編輯後,我看到下面的錯誤

ActiveRecord::StatementInvalid at /admin/industry_matchers/11/edit PG::UndefinedColumn: ERROR: column staffrooms.industry_matcher_id does not exist LINE 1: ...affrooms" WHERE "staffrooms"."deleted" = 'f' AND "staffroom... ^: SELECT "staffrooms".id FROM "staffrooms" WHERE "staffrooms"."deleted" = 'f' AND "staffrooms"."industry_matcher_id" = 11 AND (staffroom_type = 'Industry')

回答

0

你的關聯是不完整的,你必須告訴你的模型使用使用has_many through:,這樣的連接表:

class IndustryMatcher < ActiveRecord::Base 
    has_many :industry_matcher_staffrooms 
    has_many :industries, through: :industry_matcher_staffrooms, class_name: 'Staffroom', conditions: ["staffroom_type = 'Industry'"] 

class Staffroom < ActiveRecord::Base 
    has_many :industry_matcher_staffrooms 
    has_many :industry_matchers, through: :industry_matcher_staffrooms 

既然你沒有指定你的模型使用join表(即IndustryMatcherStaffroom模型),軌道對待你的協會評爲一個一對多連接,並尋找相關的ID (即industry_matcher_id)在staffrooms表,從而錯誤:

PG::UndefinedColumn: ERROR: column staffrooms.industry_matcher_id does not exist 

你可以閱讀更多有關Rails guides關聯。

+0

謝謝,但這給了一個錯誤NameError - 未定義的局部變量或方法'industry_matcher_staffrooms',我甚至嘗試在它上面添加has_many:industry_matcher_staffrooms – Saadia

+0

@Saadia對不起,我錯過了':industry_matcher_staffrooms'中的':'。查看更新後的答案。 – Gerry

+0

@Saadia無需額外的'的has_many:industry_matcher_staffrooms',只要使用'通::industry_matcher_staffrooms'。 – Gerry