我是 Rails 菜鸟,但我仍在努力思考查询关联数据的工作原理。这是我的简单架构:
create_table "microposts", :force => true do |t|
t.text "content"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "name"
t.string "email"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
我的协会如下:
class Micropost < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :user
accepts_nested_attributes_for :user
end
class User < ActiveRecord::Base
attr_accessible :email, :name
has_many :microposts
accepts_nested_attributes_for :microposts
end
我想要做的是查询我的微博,使其包含与用户表中用户名相对应的作者属性。这是我的html:
<% @microposts.each do |micropost| %>
<tr>
<td><%= micropost.content %></td>
<td><%= micropost.user_id %></td>
<td>
**<%= micropost.author %>**
</td>
<td><%= link_to 'Show', micropost %></td>
<td><%= link_to 'Edit', edit_micropost_path(micropost) %></td>
<td><%= link_to 'Destroy', micropost, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
如何在上面的一个单元格中获得类似 microposts.author 的属性?我尝试查询 Microposts.users.name 但它似乎返回 ruby 对象数据,如下所示:
[#<Micropost id: 1, content: "Though good for getting a general overview of Rails...", user_id: 2, created_at: "2012-09-02 01:52:47", updated_at: "2012-09-02 01:52:47">, #<Micropost id: 2, content: "This is another", user_id: 2, created_at: "2012-09-02 01:53:09", updated_at: "2012-09-02 01:53:09">, #<Micropost id: 3, content: "A close cousin of create_table is change_table,
更重要的是,数据中没有提及用户名数据。我究竟做错了什么?我怎么micropost.author
去上班?