2015-12-30 94 views
-1

我在Rails 4中製作一個應用程序。我使用簡單表單來創建表單。Rails簡單表單從數組中選擇 - 多態關聯

我有一個配置文件模型和組織模型。

的關聯是:

profile.rb

has_one :organisation, as: :orgable 

organisation.rb

has_many :profiles 

在我的組織表,我有一個名爲屬性:org_type。

在我的組織形式,我要求用戶從組織類型的數組中選擇:

<%= f.input :org_type, :label => "Organisation type", collection: [ "University", "Research Organisation", "Company"] %> 

在我的個人資料的形式,我想問問他們在研究,UNI用戶。

我想使用在組織模型中創建的大學數組。

我有一個範圍,我的組織模型篩選出大學:

scope :all_uni, -> { where(org_type: 'University') } 

在我的個人資料表格,我有:

<%= f.input :institution, :label => "Graduated from" %> 

但是,這只是有一個文本字段。

我試圖用我的表單中的一個選擇函數來替換該行,它引用了我的組織模型範圍all_uni。它看起來像這樣:

<%= f.select(:institution, @organisation.all_uni.title.map { |value| [ value, value ] }) %> 

它給這個錯誤:

undefined method `all_uni' for nil:NilClass 

我不明白這是什麼錯誤消息意味着,但我也不能確定我是在正確的軌道上表單選擇字段。任何提示,看看在哪裏得到這個工作。我不知道如何去設置選擇領域的第一個地方?

另一種嘗試:

我已經在我的個人資料的形式使用,這也試過:

<%= f.select(:institution, @organisation.all_uni.title) %> 

,但我得到了同樣的錯誤。我必須走出軌道 - 我已經用盡了所有我能找到的選擇。

另一種嘗試

我發現這個職位 Rails Simple Form custom association select field

以在該解決方案的例子,我想:

<%= f.input :institution do %> 
        <%= f.select :institution, Profile.Organisation.all_uni.map{ |l| [l.title {:title => l.title.titlecase}] } %> 
        <% end %> 

但是,我得到這個語法錯誤。我嘗試刪除=>但不斷收到更多的語法錯誤。

syntax error, unexpected =>, expecting '}' ...i.map{ |l| [l.title {:title => l.title.titlecase}] });@out... ...^

回答

0

不是一個完整的答案,但根據我所知道的是,如果你有2種型號,然後而是採用

profile.rb 
has_one :organisation, as: :orgable 

organisation.rb 
has_many :profiles 

,你可以簡單地使用

profile.rb  
belongs_to :organisation 

organisation.rb  
has_many :profiles 
+0

嗨惡意軟件。謝謝。在模型是多態時需要額外的位。無論如何非常感謝。 – Mel