2016-12-11 3 views
0

사용자를 기반으로 새 이벤트를 만들려고 할 때 레일즈 콘솔에 문제가 발생했습니다. 나는 이것이 매우 단순한 오류라는 느낌을 갖지만, 나는 그것을 어떻게 고쳐야하는지 확신 할 수 없기 때문에 게시하고있다.트랜잭션 롤백 콘솔 롤백

다음
class CreateEvents < ActiveRecord::Migration[5.0] 
    def change 
    create_table :events do |t| 
     t.string :name 

     t.timestamps 
    end 
    end 
end 

내 사용자 데이터베이스 파일입니다 : 여기

user.event = Event.create(:name => "Dummy") 

내 이벤트에 대한 내 DB 파일입니다 : 여기
class CreateUsers < ActiveRecord::Migration[5.0] 
    def change 
    create_table :users do |t| 
     t.string :name 
     t.string :email 
     t.string :event 
     t.integer :code 


     t.timestamps 
    end 
    end 
end 

내 사용자됩니다 여기에 내가 실행하려고 명령은 .rb 파일 :

class User < ApplicationRecord 
    has_secure_password 
    has_many :events 

    def User.digest(string) 
     cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost 
     BCrypt::Password.create(string, cost: cost) 
    end 
end 

여기 있습니다 t.rb 파일 :

class Event < ApplicationRecord 
    belongs_to :user 
end 

답변

1

테이블에 외래 키가 없습니다. 설명 된대로 실제로 모델을 만들려고한다고 가정하면 ("이벤트는 사용자에게 속합니다"/ "사용자는 많은 이벤트가 있음"), user_id 열을 이벤트 테이블에 추가하고 event 문자열을 users 테이블에 추가해야합니다.

당신은 이동/모델 발전기가 references 유형을 사용하여 마이그레이션 또는 열 정의를 만들 수 있습니다

rails g model event name:string user:references 

또는

rails g migration add_user_id_to_event user:references 

열 및 필요한 인덱스를 추가 할 것이다. 또한

, 당신은 사용자가 많은 이벤트를 가지고, 그래서

user.event = Event.create 

같은 것이없는 대신

user.events << Event.create(...) 
1

그것의 아닌 (그런 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_idevent_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에 열을 추가하는 것입니다 해결하기 위해 협회가 무엇인지 지정 모델을 가입 할 수 있습니다. 그러나 이것은 당신의 기술 수준을 훨씬 뛰어 넘습니다.

+0

내 문제에 대해 매우 깊이있는 설명을 해주셔서 감사합니다. 나는 협회가 일하도록 끝내었다. 나의 마지막 질문은 각 사용자에게 이벤트를 할당하는 것입니다. 내 응용 프로그램의 주요 목적은 사용자가 Partys를 가지고 있고 해당 당사자가 노래를 만들도록하는 것입니다. 이 신청서에 올바른 방향으로 가고 있습니까? – Aaron

+0

레일 가이드 [관련 기사] (http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association)와 [활성 레코드 쿼리 인터페이스] (http : //guides.rubyonrails.org/active_record_querying.html#joining-tables). – max

+0

좋습니다. :) – Aaron