0
我創建一個應用程序登錄時,文件被移動到備份驅動器,他們來自何處以及被轉移到哪些用戶移動它們。我在做什麼錯誤使用Rails的has_many和belongs_to的關聯?
這是我的歸檔模式:
class Archive < ActiveRecord::Base
attr_accessible :archive_date, :start_dir, :end_dir, :user_id
#added by chris
belongs_to :user
end
這是我的用戶模型:
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'
假設檔案記錄正確保存與用戶USER_ID我如何得到我的觀點通過的has_many belongs_to的關聯,顯示用戶的名字嗎?
謝謝你看我的問題。
這完美地工作。 – holaSenor 2012-01-27 16:10:47