有这样的二层表结构,父表users,子表books.需要在显示books的时候,显示user的username,而不是user_id.
请问如何才能在下面的view代码中显示到username的数据呢?
我用的是ROR 2.0
Model
[code="ruby"]
class Book < ActiveRecord::Base
belongs_to :user, :class_name => "Book", :foreign_key=>"user_id"
end
class User < ActiveRecord::Base
has_many :books
end
[/code]
Controller
[code="ruby"]
class BooksController < ApplicationController
def index
@books = Book.find(:all)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @books }
end
end
end
[/code]
View
[code="ruby"]
<% for book in @books %>
<%=h book.title %>
<%=h book.description %>
<%=h book.user_id %>
<%=h book.cover %>
<%= link_to 'Show', book %>
<%= link_to 'Edit', edit_book_path(book) %>
<%= link_to 'Destroy', book, :confirm => 'Are you sure?', :method => :delete %>
<% end %>
[/code]
[b]问题补充:[/b]
花花公子,按你说的,得到报错如下,
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.user
估计您说的是<%= h book.user.username %> 吧。
这个我之前也试过,但一样是报错:
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.username
[b]问题补充:[/b]
<%= book.user ? book.user.username : '' %>
运行后,没有值显示。应该是book.user不存在吧。
是不是要在model中添加些什么才行?
还是因为user是关键字?