I’m creating an app to log when files are moved to an archive drive, where they came from and were moved to and what user moved them.
This is my Archive model:
class Archive < ActiveRecord::Base
attr_accessible :archive_date, :start_dir, :end_dir, :user_id
#added by chris
belongs_to :user
end
This is my User model:
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
This is my view:
<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>
When I start up my local rails server via rails s Try to load the page. This is what I get:
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'
Assuming the archive record is correctly saved with the users User_ID how do i get my view to display the name of the user via the has_many belongs_to association?
Thank You for looking at my question.
Archives have users, users have usernames–I think you’re just up one level to “high”; use: