2012-01-27 16 views
0

私は、ファイルをアーカイブドライブに移動したときにログを記録するアプリケーションを作成しています。Rails has_manyとbelongs_to associationには何が間違っていますか?

これは私のアーカイブモデルです:

class Archive < ActiveRecord::Base 
    attr_accessible :archive_date, :start_dir, :end_dir, :user_id 

    #added by chris 

    belongs_to :user 
end 

これは私のUserモデルである:

class User < ActiveRecord::Base 
    # new columns need to be added here to be writable through mass assignment 
    attr_accessible :username, :email, :password, :password_confirmation, :user_id 

    attr_accessor :password 
    before_save :prepare_password 
    before_save :assign_user_id 

    #added by chris 
    has_many :archives 

    def assign_user_id 
    self.user_id = User.maximum('user_id') + 1 
    end 

end 

これが私の見解です:

<table id="archive_table"> 
    <tr> 
    <th>Archive Date</th> 
    <th>Source Directory</th> 
    <th>Archive Directory</th> 
    <th>Archived By ID</th> 
    <th>Archived By Name</th> 
    </tr> 
    <% for archive in @archives %> 
    <tr> 
     <td><%= archive.archive_date %></td> 
     <td><%= archive.start_dir %></td> 
     <td><%= archive.end_dir %></td> 
     <td><%= archive.user_id %></td> 
     <td><%= archive.username %></td> 
     <td><%= link_to "Show", archive %></td> 
     <td><%= link_to "Edit", edit_archive_path(archive) %></td> 
     <td><%= link_to "Destroy", archive, :confirm => 'Are you sure?', :method => :delete %></td> 
    </tr> 
    <% end %> 
</table> 

<p><%= link_to "New Archive", new_archive_path %></p> 

私は私の地元のレール・サーバを起動します経由でrails sページを読み込もうとします。

NoMethodError in Archives#index 

Showing c:/appname/app/views/archives/index.html.erb where line #21 raised: 

undefined method `username' for #<Archive:0x203d750> 

Extracted source (around line #21): 

18:  <td><%= archive.start_dir %></td> 
19:  <td><%= archive.end_dir %></td> 
20:  <td><%= archive.user_id %></td> 
21:  <td><%= archive.username %></td> 
22:  <td><%= link_to "Show", archive %></td> 
23:  <td><%= link_to "Edit", edit_archive_path(archive) %></td> 
24:  <td><%= link_to "Destroy", archive, :confirm => 'Are you sure?', :method => :delete %></td> 

Rails.root: c: 
Application Trace | Framework Trace | Full Trace 

app/views/archives/index.html.erb:21:in `block in _app_views_archives_index_html_erb__238412483_16592988' 
app/views/archives/index.html.erb:15:in `each' 
app/views/archives/index.html.erb:15:in `_app_views_archives_index_html_erb__238412483_16592988' 

は、アーカイブのレコードが正しくどのように私は関連belongs_toのにhas_manyを介してユーザの名前を表示するように私の見解を得るのですかUSER_IDユーザーと一緒に保存されたと仮定すると:これは私が何を得るのですか?

私の質問をご覧いただきありがとうございます。

答えて

2

アーカイブにはユーザーがいますが、ユーザーにはユーザー名があります。

<%= archive.user.username %> 
+0

これは完全に機能しました。 – holaSenor

関連する問題