Rails - Many-to-Many Relationship - Data Issue?
I have a pretty newb question, about a many-to-many relationship I've created, and pulling the correct data from the child.
What I have is 2 Models, one called Order and another Status. I have a migration named CreateOrdersStatuses to join the two tables.
In the ruby console, I'm having difficulties pulling information of the child via the parent, for example:
I have assigned my first order a status, and the console gives me the following read out:
ruby-1.9.2-p0 > order.statuses
=> [#<Status id: 1, name: "New", create开发者_如何学Pythond_at: "2010-11-18 20:19:12", updated_at: "2010-11-18 20:19:12">]
However, for my view, I'm trying to display an order's status, so I've been trying the following in the console order.statuses.name - which I thought would give me the print out of "New". Instead I'm only able to pull "Status" when attempting this. For example:
ruby-1.9.2-p0 > order.statuses.name
=> "Status"
I believe my issue is syntax related when trying to pull my order's status name? I can provide the models/migrations if necessary, I was just thinking it is a syntax issue since I'm a newb :).
Thanks all.
order.statuses.name
won't return "New", because order.statuses
is a collection (you see rectangular brackets in your first output). So there's no sense in doing order.statuses.name
. You can do order.statuses[0].name
, for instance.
Nevertheless, order.statuses.name
doesn't throw an error, because an association actually has a method name
that returns the name of the association's class. In your case the class of statuses
association is Status
, so this method returns "Status".
To avoid icky array-index notation "[0]", you can do instead:
order.statuses.first.name
assuming that your Order model
has_many :statuses
精彩评论