2011-10-11 33 views
0

我不明白如何從我的View中訪問其他表中的數據。Rails:在View中訪問其他SQL表的數據

我有幾個型號。首先是用戶,其次是UsersPreferences。所以,我對於用戶設置頁,代碼如下:

<%= render 'shared/error_messages', :object => f.object %> 
<div class="field"> 
    <%= f.label  :name %><br /> 
    <%= f.text_field :name %> 
</div> 
... 
<div class="checkbox"> 
    <%= f.check_box :notification_about_new_followers %>       
    <%= f.label  'Notify via email about new followers' %><br /> 
</div> 

此代碼(用戶有排notification_about_new_followers),但我想改變它。我決定更好的方法是在其他表格中保留偏好。所以我創建了用戶偏好其中user_id和標誌'notify_about_new_followers'。我試圖重寫我的觀點類似:

<%= render 'shared/error_messages', :object => f.object %> 
<div class="field"> 
    <%= f.label  :name %><br /> 
    <%= f.text_field :name %> 
</div> 
... 
<div class="checkbox"> 
    <%= f.check_box UsersPreferences.find_by_user_id(@user.id).notify_about_new_followers %>       
    <%= f.label  'Notify via email about new followers' %><br /> 
</div> 

但是當我訪問網頁的代碼,我得到這樣的錯誤

undefined method `true' for #<User:0x007f8ac180dee8> 

我怎樣才能解決這個問題?

用戶模型:

class User < ActiveRecord::Base 
    attr_accessible :name, ... , :notification_about_new_followers 
    ... 
    has_one :users_preferences 
end 

UsersPreferences模型:

class UsersPreferences < ActiveRecord::Base 
    belongs_to :user, :class_name => "User" 
    attr_accessible :notify_about_new_followers 
end 
+0

在你遇到一些不良習慣之前,請[很熟悉MVC](http://jordanhall.co.uk/programming/simple-explanation-of-model-view-controller-mvc-2206990/)。 – bricker

回答

1

這條線:

<%= f.check_box UsersPreferences.find_by_user_id(@user.id).notify_about_new_followers %> 

導致錯誤。 UsersPreferences.find_by_user_id(@user.id).notify_about_new_followerstrue,所以本質上是一行:

<%= f.check_box true %> 

而像錯誤說,沒有「真」屬性爲您的模型使用UserPreferences。

要解決這個問題,您需要先閱讀MVC(模型 - 視圖 - 控制器)。不知道MVC是如何工作的,你將永遠無法前進Rails。有很多很棒的資源,只有google "Model View Controller for rails"Here is a good one。有點愚蠢,雖然...如果這不是你的風格,嘗試另一個鏈接。

當你瞭解到這一點之後,查看護欄助手fields_for,在那裏你會找到你的答案。