简体   繁体   中英

Connecting two models in rails

I am trying to call value from another model inside the views.

tse.headoffice.head_office_id

Defined the relationship in headoffice.rb as

has_many :tse

and in tse.rb as

belongs_to :headoffice

Now I am getting an error as undefined method

undefined method `head_office_id' for nil:NilClass

<% if tse.headoffice.present? %>
  <%= tse.headoffice.head_office_id %>
<% end %>

try()使您可以在对象上调用方法,而不必担心该对象为nil的可能性,从而引发异常

<%= tse.try(:headoffice).try(:head_office_id) %>

Assuming that the HeadOffice model has an attribute called head_office_id :

<%= tse.headoffice.head_office_id if tse.headoffice %>

If that's not the case:

<%= tse.headoffice_id %>

Something about this doesn't look right. Usually the has_many reference is plural. It's possible your naming scheme is messing with Rails' opinionated magic.

Also why would headoffice have a field called headoffice_id ? Wouldn't it just have a field called id ? Finally, one nitpick, it should be called head_office not headoffice . And tse is not a good name either. What is tse ? Spell it out if you can and form it in a manner that can be singular or plural. Rails works much better if you follow these simple naming guidelines.

https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e

See the simple example below:

post.rb

has_many :comments

comment.rb

belongs_to :post

To access a post's comments you'd type the following:

Post.first.comment.body

Or if you're uncertain about a post having a comment you'd say:

Post.first.try(:comment).try(:body)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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