Ruby on Rails的 - 从的has_many台秀场 [英] Ruby on Rails - Show field from has_many table

查看:85
本文介绍了Ruby on Rails的 - 从的has_many台秀场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表:船舶和远航。船舶可以有很多的航程,但航程可能只有一个船。

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

在回报率船模型具有的has_many:航行和航行模式设置为belongs_to的:船

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

我可以用code相似,这没有任何问题的看法显示所有从船上表中的字段:

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.

如果我做的:

<%= @ship_data.voyages %> 

我能拉起的ActiveRecord项,即:

I'm able to pull up the ActiveRecord entry i.e.:

#<Voyage::ActiveRecord_Associations_CollectionProxy:0x00000006639a10>

如果我追加.to_json我可以拉起一个JSON文件的所有数据。

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

<%= @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 是一个ActiveRecord的关系。这就像项目的数组。你可以得到每个项目的ID数组:

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

或者只得到第一远航:

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

这篇关于Ruby on Rails的 - 从的has_many台秀场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆