简体   繁体   中英

Ruby on Rails - Show field from has_many table

I've got two tables: Ships and Voyages. A ship can have many voyages, but a voyage may only have one ship.

In RoR the ship model has a has_many :voyages and the Voyage model is set to belongs_to: ship

I can display all of the fields from the ship table in the view without any problems using code similar to this:

<%= @ship_data.id %>

I'm now trying to show a piece of information from the voyage table in the view.

If I do:

<%= @ship_data.voyages %> 

I'm able to pull up the ActiveRecord entry ie:

#<Voyage::ActiveRecord_Associations_CollectionProxy:0x00000006639a10>

If I append .to_json I can pull up a json file with all the data.

How would I go about displaying a specific field in my view, things I've tried include:

<%= @ship_data.voyages.id %>

and

<%= @ship_data.voyages, :id %>

But both error out on me. Note: While the relationship is one ship to many voyages - currently each ship only has one voyage.

I will admit to being a bit of a RoR novice!

@ship_data.voyages is an ActiveRecord relation . It's like an array of items. You can get an array of ids of every item:

<%= @ship_data.voyages.pluck(:id) %>

Or loop through the array:

<% @ship_data.voyages.each do |voyage| %>
    <%= voyage.id %>
<% end %>

Or get only first voyage:

<%= @ship_data.voyages.first.id %>

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