jeudi 2 avril 2015

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


Aucun commentaire:

Enregistrer un commentaire