简体   繁体   English

Rails-获取协会的所有者

[英]Rails - Get the owner of the association

Hey. 嘿。 I'm starting in Rails and I guess my question is pretty easy. 我从Rails开始,我想我的问题很简单。 I have 2 models: 我有2个型号:

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. 我正在尝试通过show方法获取这本书的所有者,但是我所做的一切都表明我找不到没有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! 谢谢!

Follow the relationship from the book to the owner, you don't even have to do this in the controller. 遵循书籍与所有者之间的关系,您甚至不必在控制器中执行此操作。

def show
  @book = Book.find(params[:id])
end

In your views: 在您看来:

<%= link_to @book.owner.name, @book.owner %>

As you are using belongs_to :owner you can use it like this: 在使用belongs_to :owner您可以像这样使用它:

def show
  @book = Book.find(params[:id])
  @owner= book.owner
end

In your view you have to use these global @ variables: @book, @owner . 在您看来,您必须使用以下全局@变量: @ @book, @owner @ @book, @owner book and owner won't work. bookowner将无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM