开发者

How best to do in this situation?

I have tree model Meeting , Client, Contact.

When i create new mee开发者_运维知识库ting, i can select client or contact , but how better store this structure and association? !Use case client_id and contact_id in meeting table not good.


We assume someone (a creator) can create a meeting. The creator may be a client or a contact.

For that you need a "creator_type" and "creator_id" column on your Meetings Table first, so add an migration using script/rails generate migration AddTypeToMeetings

Then edit the migration file like:

class AddTypeToMeetings < ActiveRecord::Migration
  def self.up
    add_column  :meetings, :creator_id, :integer
    add_column  :meetings, :creator_type, :string
  end
end

Second, you have to adapt your models:

meeting.rb

class Meeting < ActiveRecord::Base
  # polymorphic association
  belongs_to  :creator, :polymorphic => true

end

client.rb

class Client < ActiveRecord::Base
  has_many  :meetings, :as => :creator
end

contact.rb

class Contact < ActiveRecord::Base
  has_many  :meetings, :as => :creator
end

How to use:

@my_meeting = Meeting.new

@my_meeting.creator = @my_client
# or if you want a contact:
@my_meeting.creator = @my_contact

You can read more up on polymorphic associations here:

  • ASCII Casts
  • Documentation (scroll to Polymorphic Association)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜