Ruby on Rails - Show field from has_many table

吃可爱长大的小学妹 提交于 2020-01-06 19:33:19

问题


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 i.e.:

#<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!


回答1:


@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 %>


来源:https://stackoverflow.com/questions/29423675/ruby-on-rails-show-field-from-has-many-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!