Search code examples
ruby-on-railsrubyentity-relationship

Is there any wrong in my object relationship?


I want which order have different order status, so I have a table called "status", in the status.rb, it likes this:

class Status < ActiveRecord::Base
  belongs_to :order 
  attr_accessible :name

end

And this is my order.rb:

class Order < ActiveRecord::Base
  has_one :statuses
end

In my view, I try to call the related status like this:

    <%= order.statuses.name%>

It don't work, so , I called it in this way:

<% order.statuses.each_with_index do |order_status, index| %>
<%= order_status.name%>
<% end %>

It still don't work. I have the error like this:

uninitialized constant Order::Statuses

I changed my code to this:

It should be

has_one :status

and

order.status.name

But I have this error:

SQLite3::SQLException: no such column: statuses.order_id: SELECT * FROM "statuses" WHERE ("statuses".order_id = 5) LIMIT 1

I only want the order related to the status, but the status is not related to the order, can I do so?


Solution

  • You're getting an error because of pluralization. You should have:

    class Order < ActiveRecord::Base
      has_one :status
    end
    

    However, it sounds like you might have the belongs_to - has_one relationship backwards. If you only want to have only a few statuses in the database (eg: pending, billed, shipped, complete), a Status should has_many orders, and each Order should belongs_to a Status. The way you have it set up now, there will be a separate Status object for each Order. This may be what you want, but make sure you understand that it implies that every status is different (maybe each is a sentence or two describing the order).