-1

외래 키 연관을 사용하여 표 A를 참조하는 표 B에 데이터를 삽입하려고합니다.
여기 내 코드입니다. 지금은 레일 콘솔의 StudentStatusReport 모델에 데이터를 삽입하려면 다음 쿼리를 사용하고레일 3 : 맞춤형 FK 및 PK를 수용 할 수있는 레일 오버라이드

class CreateStudentDetails < ActiveRecord::Migration 
    def change 
    create_table :student_details, {:id => false} do |t| 
    t.string :student_id 
    t.string :name 
    t.timestamps 
    end 
    execute "ALTER TABLE student_details ADD PRIMARY KEY (reg_no);" 
end 
end 


class CreateStudentStatusReports < ActiveRecord::Migration 
    def change 
    create_table :student_status_reports do |t| 
    t.string :student_id 
    t.integer :mark 
    t.timestamps 
    end 
end 
end  

을 다음과 같이

models.rb

class StudentStatusReport < ActiveRecord::Base 
attr_accessible :student_id, :mark 
belongs_to :student_details, :class_name => "StudentDetails", :foreign_key => "student_id" 
end 

class StudentDetails < ActiveRecord::Base 
attr_accessible :student_id, :name 
has_many :student_status_reports 
end 

및 Migrations.rb입니다.

e = StudentDetails.find("UG10001") 
f = e.student_status_reports.create!(:mark => 40) 

하지만 콘솔에 다음과 같은 오류가 무엇입니까 -

ActiveRecord::UnknownAttributeError: unknown attribute: student_details_id 

는 어떤이에 대한 가능한 해결책이 될 수 있습니까?
모델과 데이터베이스에서 외래 키와 기본 키를 이미 정의 했으므로 어디에서 잘못 될지 알 수 없습니다. Tx ..!

답변

1

문제는 외래 키라고 생각합니다. StudentStatusReport 모델에서는 student_status_reports 테이블에 student_id 열로 정의하지만 StudentDetails 모델에서는 student_details_id으로 정의됩니다 (명시 적으로 정의하지 않는 한 Rails는 연결 이름 + _id으로 추측합니다). 그래서 오류가 parent_model 올바른 foreign_key를 지정하여 고칠해야합니다

class StudentStatusReport < ActiveRecord::Base 
    attr_accessible :student_id, :mark 
    belongs_to :student_details, :class_name => "StudentDetails", :foreign_key => "student_id" 
end 

class StudentDetails < ActiveRecord::Base 
    attr_accessible :student_id, :name 
    has_many :student_status_reports, :foreign_key => "student_id" 
end 

student_details 테이블의 student_id 열이 실제로 관련하여 사용하지 않는, 그래서 당신은 더 많은 연결을 만들기 위해를 제거하는 것이 좋습니다하는 것으로 명확한.

마지막으로 Rails의 기본 규칙 (id이라는 정수 자동 증가 기본 키, 단일 모델 이름)을 고수하는 것이 좋습니다. 하지만 때때로 당신은 할 수 없습니다 ... : S

+0

감사합니다. @deivid .. 그것은 잘 작동합니다. uplz 내 다른 질문 plz 봐 수 있습니다 .http : //stackoverflow.com/questions/14935143/how-to-access-a-newly-created-column-in-sql-table-using-rails-3-1 –

+0

나는 당신을 도우려고했지만 분명히 그것을 제거했습니다 ... 경례. – deivid

+0

그것은 절대적으로 불합리한 질문 이었기 때문에 삭제했습니다. 나는 RoR이 거의 모든 기지를 덮었다는 것을 몰랐다. 바보 같은 녀석! 어쨌든 고마워.. –