我在Rails has_many和belongs_to协会上做错了什么?

时间:2012-01-27 15:38:33

标签: ruby-on-rails-3

我正在创建一个应用程序来记录何时将文件移动到存档驱动器,它们来自哪里并被移动到用户移动它们。

这是我的档案模型:

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启动本地rails服务器时尝试加载页面。这就是我得到的:

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关联获取我的视图以显示用户名?

感谢您查看我的问题。

1 个答案:

答案 0 :(得分:2)

档案馆有用户,用户有用户名 - 我认为你只有一级到“高”;使用方法:

  <%= archive.user.username %>