Rails - 获取关联的所有者
嘿。我从 Rails 开始,我想我的问题很简单。我有 2 个模型:
class Book < ActiveRecord::Base
belongs_to :owner
end
class Owner < ActiveRecord::Base
has_many :books
end
我试图通过 show 方法获取这本书的所有者,但我所做的一切都表明我无法找到没有 ID 的所有者。
我的控制器有:
def show
@book = Book.find(params[:id])
@owner= Owner.find(params[:owner_id])
end
我的观点:
<%= link_to owner.name, owner %>
谢谢!
Hey. I'm starting in Rails and I guess my question is pretty easy. I have 2 models:
class Book < ActiveRecord::Base
belongs_to :owner
end
class Owner < ActiveRecord::Base
has_many :books
end
I'm trying to get the owner of the book on the show method, but everything I do says I can't find an Owner without an ID.
My controller has:
def show
@book = Book.find(params[:id])
@owner= Owner.find(params[:owner_id])
end
And my view:
<%= link_to owner.name, owner %>
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
遵循书中与所有者的关系,您甚至不必在控制器中执行此操作。
在您看来:
Follow the relationship from the book to the owner, you don't even have to do this in the controller.
In your views:
当您使用
belongs_to :owner
时,您可以像这样使用它:在您看来,您必须使用这些全局
@
变量:@book, @owner.
book
和owner
不起作用。As you are using
belongs_to :owner
you can use it like this:In your view you have to use these global
@
variables:@book, @owner
.book
andowner
won't work.