clickbird 2008-10-23 23:24
浏览 230
已采纳

ROR中如何取得父表的数据?

有这样的二层表结构,父表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是关键字?

  • 写回答

3条回答 默认 最新

  • iteye_1187 2008-10-24 00:14
    关注

    [code="ruby"]
    <%= h @book.user.username %>
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?