2011-10-11 4 views
0

내 테이블에서 다른 테이블에 액세스하는 방법을 이해하지 못합니다.레일 :보기에서 다른 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'인 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 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 (Model-View-Controller)에서 먼저 읽어야합니다. MVC가 어떻게 작동하는지 알지 못해도 Rails로는 앞으로 나아갈 수 없습니다. 밖에 많은 훌륭한 리소스가 있습니다. 단지 google "Model View Controller for rails"입니다. Here is a good one. 그래도 조금 바보 같아서 ... 당신 스타일이 아니라면 다른 링크를 시도해보십시오.

배운 후에는 레일 도우미 fields_for을 찾아 보면 대답을 찾을 수 있습니다.

관련 문제