그것의 아닌 (그런 User#event=
등의 방법이 없음) 간단한 오류. 틀린 몇 가지 사항입니다.
사용자가 많은 이벤트를 가질 수 있고 이벤트가 많은 사용자에게 속할 수있는 관계를 원할 경우 조인 테이블을 작성해야합니다. 사용자 또는 이벤트 테이블에 외래 키를 저장하면 일대 다 관계가 생길 수 있는데, 이는 아마도 원하는 것이 아닙니다.
class User < ApplicationRecord
has_many :user_events
has_many :events, through: :user_events
end
class Event < ApplicationRecord
has_many :user_events
has_many :users, through: :user_events
end
# this is a join model.
class UserEvent < ApplicationRecord
belongs_to :user
belongs_to :event
end
has_many :through association
는 종종 다른 모델 대다 연결을 설정하는 데 사용됩니다. 이 연결은 모델을 선언 할 때 세 번째 모델을 진행하여 다른 모델의 인스턴스가 0 개 이상 일치 할 수 있음을 나타냅니다.
rails g model user_event user:belongs_to event:belongs_to
이는 user_id
및 event_id
외래 키 열이있는 user_events
테이블을 생성합니다 : http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
당신은 UserEvent
모델과 실행하여 테이블을 조인 생성하는 마이그레이션을 생성 할 수 있습니다. 또한 사용자 테이블을 작성 마이그레이션을 롤백하고 해결해야합니다
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :password_digest # !!!
t.integer :code
t.timestamps
end
end
end
참고 password_digest
열을 추가 -이는 has_secure_password
필요합니다. 당신이 할 수있는 사용자와 관련된 이벤트를 만들려면
class AddPasswordDigestToUsers < ActiveRecord::Migration[5.0]
def change
add_column(:users, :password_digest, :string)
end
end
class RemoveEventFromUsers < ActiveRecord::Migration[5.0]
def change
remove_column(:users, :event)
end
end
: 이미 프로덕션 데이터베이스 또는 커밋에이 마이그레이션을 실행하고 밀어 경우 대신 오류를 수정 별도의 마이그레이션을 만들어야합니다 :
user.events << event
event.users << user
,691 :
event = user.events.new(name: "Dummy") # does not persist the record
event = user.events.create(name: "Dummy")
당신은 모든 삽 연산자를 사용하여 양쪽 끝에서 레코드를 할당 할 수 있습니다
나에게 적합한 협회인가요? 내 응용 프로그램에 대한
내 주요 목표는 그렇게 사용자가 당사자의를 가지고 그 당사자가 노래를 만드는 것입니다.
단 한 명의 사용자가있는 파티는 꽤 절름발이입니다. 그러나 당신은 당신이 별도의 연결을 만들 수있는 사용자를위한 특별한 관계를 만들려면 :
class User < ApplicationRecord
has_many :user_events
has_many :events, through: :user_events
has_many :owned_events, class_name: 'Event', foreign_key: 'owner_id'
end
class Event < ApplicationRecord
has_many :user_events
has_many :users, through: :user_events
belongs_to :owner, class_name: 'User'
end
class AddOwnerIdToEvents < ActiveRecord::Migration[5.0]
def change
add_column(:events, :owner_id, :integer)
add_foreign_key(:events, :users, column: :owner_id)
end
end
또 다른 방법이 UserEvent
에 열을 추가하는 것입니다 해결하기 위해 협회가 무엇인지 지정 모델을 가입 할 수 있습니다. 그러나 이것은 당신의 기술 수준을 훨씬 뛰어 넘습니다.
내 문제에 대해 매우 깊이있는 설명을 해주셔서 감사합니다. 나는 협회가 일하도록 끝내었다. 나의 마지막 질문은 각 사용자에게 이벤트를 할당하는 것입니다. 내 응용 프로그램의 주요 목적은 사용자가 Partys를 가지고 있고 해당 당사자가 노래를 만들도록하는 것입니다. 이 신청서에 올바른 방향으로 가고 있습니까? – Aaron
레일 가이드 [관련 기사] (http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association)와 [활성 레코드 쿼리 인터페이스] (http : //guides.rubyonrails.org/active_record_querying.html#joining-tables). – max
좋습니다. :) – Aaron