Assumptions
- This is a system for many users, not just one, so you need to specify the owner in the Contact and Group entries using a foreign key.
- A contact can belong to several groups, and a group has several contacts, so this has_and_belongs_to_many relationship.
Migration
Create user table:
class CreateUsers < ActiveRecords::Migrations
def change
create_table :users do |t|
t.text :username
end
end
end
. , , , .
class CreateContacts < ActiveRecord::Migrations
def change
create_table :contacts do |t|
t.references :owner
t.references :user
end
end
end
. , .
class CreateGroups < ActiveRecord::Migrations
def change
create_table :groups do |t|
t.references :owner
t.text :name
end
end
end
has_and_belongs_to_many . ; , .
class CreateContactsGroups < ActiveRecord::Migrations
def change
create_table :contacts_groups do |t|
t.references :contact
t.references :group
end
end
end
. , , , - "owner_id". .
class User
has_many :contacts, :foreign_key => 'owner_id'
has_many :groups, :foreign_key => 'owner_id'
end
. , "" . , Contact ( Rails-, ), : , , : . , .
class Contact
belongs_to :owner, :class_name => 'User'
belongs_to :user
has_and_belongs_to_many :groups
end
. .
class Group
belongs_to :owner, :class_name => 'User'
has_and_belongs_to_many :contacts
end
contacts_groups, .
, :
@user.contacts
@user.groups
@user.groups.find(id).contacts
@user.contacts.find(id).groups
@benrmatthews, .
, , Contact ID , contact_groups, , .
:
resources :contact_groups, only: [:create]
, :
class ContactGroupsController < ApplicationController
def create
@contact = Contact.find(params[:contact_id])
@group = Group.find(params[:group_id])
@contact.groups << @group
end
end
, contact_id group_id . :
form_tag contact_groups_path do
hidden_field_tag :contact_id, @contact.id
select_tag :group_id, options_from_collection_for_select(Group.all, :id, :name)
submit_tag "Add to Group"
end
, contact_id select, . , contact_id group_id , , .