1

讓我解釋我想要做什麼,然後問我的問題。我是一名Ruby/Rails的新手,但他是一位經驗豐富的開發人員。在form_for中使用Rails 3中的多態關聯未定義的方法

我想要什麼:我想要開發者,客戶和管理員。我想要一個通用的認證機制。

什麼似乎是最好的:我認爲最好的方式是通過讓用戶處理身份驗證,然後進行某種類型的繼承或擴展每種用戶類型的功能。

我在想什麼:我正在嘗試稱爲多態協會(http://guides.rubyonrails.org/association_basics.html#polymorphic-associations),但我錯過了一些東西。目前,如果我去/developers/new,我得到以下

in developers/_fields.html.erb where line #4 raised: 
undefined method `name' for #<Developer:0x00000002bafd18> 

user.rb片段

class User < ActiveRecord::Base 
    attr_accessible :email, :name, :password, :password_confirmation, :profile_id, :profile_type 
    has_secure_password 
    belongs_to :profile, :polymorphic => true 
    ... 
end 

developer.rb片段

class Developer < ActiveRecord::Base 
    attr_accessible :skype_name 
    has_one :user, :as => :profile, :dependent => :destroy 
    accepts_nested_attributes_for :user 
end 

的routes.rb snippet

resources :developers 

開發新#控制器片斷

def new 
    @developer = Developer.new 
    @developer.user = User.new 
end 

new.html.erb片段用於開發

<div class="row"> 
    <div class="span6 offset3"> 
    <%= form_for (@developer) do |f| %> 
     <%= render 'fields', f: f %> 
     <%= f.submit "Create my account", class: "btn btn-large btn-primary" %> 
    <% end %> 
    </div> 
</div> 

終於 _fields.html.erb片段

<%= render 'shared/error_messages' %> 
<%= f.label :name %> 
<%= f.text_field :name %> 
... 

我發現的最接近的問題是this但我從他們的答案中嘗試了一些東西,但沒有幫助。

我可以創建一個新的用戶和開發人員,通過導軌控制檯相互鏈接,但我無法弄清楚我在做什麼錯誤的網絡。

任何幫助將不勝感激。

+0

發生錯誤的文件是什麼? – 2013-04-04 19:05:51

+0

developers/_fields.html.erb我也會編輯這個問題。感謝您指出了這一點。 – 2013-04-04 19:06:35

+0

這可能不是這樣,但它看起來像表單假設開發者有一個名字,但用戶是一個名字。有沒有辦法把'<%= f.label [user in developer object]:name%>'?或者,也許表單應該是@user,因爲這似乎是更廣泛的對象?我現在只是把這些紅寶石掛在軌道上,所以我對這裏的建議猶豫不決。 – 2013-04-04 19:14:47

回答

2

您正試圖訪問developer父級範圍內的user屬性。使用fields_for修改範圍:

<%= render 'shared/error_messages' %> 
<%= f.fields_for :user do |u| %> 
    <%= u.label :name %> 
    <%= u.text_field :name %> 
<% end %> 

你也可能會想使開發模型接受用戶的嵌套屬性。看看in the documentation的一些例子。

+1

當時,應該有信心發表一個答案!很高興知道我在正確的軌道上!我保存這個SO問題以供將來參考。 – 2013-04-04 19:23:55

+0

謝謝!它仍然是壞的,但現在由於auth檢查。我遇到的問題已解決。 – 2013-04-04 19:47:06

相關問題