开发者

Association that don't look much sense

开发者 https://www.devze.com 2023-03-23 22:32 出处:网络
I need a little help to understand this association types. I have 2 models (item_type and item) item_type it\'s just acting like a category and have only one field (title)

I need a little help to understand this association types.

I have 2 models (item_type and item)

item_type it's just acting like a category and have only one field (title)

Table structure:

item_type:

  • id
  • title
  • created_at
  • updated_at

item:

  • id
  • item_type_id
  • title
  • price
  • other irrelevant fields..

So, basicly I'm trying to do a simple association between this models.

class ItemType < ActiveRecord::Base
  belongs_to :item
end

class Item < ActiveRecord::Base
  has_one :item_type
end

I have created an item and save it, but when I'm fetching it to show, it should display the item_type.title instead of just item_type.id, right?

I've readed about that belongs_to always goes on the table that has the foreign_key, but in this case, it doesn't make much sense for me.. and even inverting the relationships, putting the has_one on the ItemType class and the belongs_to to the Item class, either this way works.

In the controller co开发者_Go百科de I have:

def show
  @item = Item.find(params[:id], :include => 'item_type')
end

And the view, should be visible to see the relationship created just with

<%= debug @item %>

What I'm doing wrong?


i remember you need to put belongs_to in the model who contain the foreign key, in your example :

class ItemType < ActiveRecord::Base
    has_one :item
end

class Item < ActiveRecord::Base
    belongs_to :item_type
end

See the documentation.

0

精彩评论

暂无评论...
验证码 换一张
取 消