activerecord - Rails 3 : Overriding rails convention to accommodate custom made FK and PK -
i trying insert info table b refers table using foreign key associations. here code.
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
and migrations.rb follows
class createstudentdetails < activerecord::migration def alter create_table :student_details, {:id => false} |t| t.string :student_id t.string :name t.timestamps end execute "alter table student_details add together primary key (reg_no);" end end class createstudentstatusreports < activerecord::migration def alter create_table :student_status_reports |t| t.string :student_id t.integer :mark t.timestamps end end end
now using next query insert info studentstatusreport model on rails console.
e = studentdetails.find("ug10001") f = e.student_status_reports.create!(:mark => 40)
but getting next error on console --
activerecord::unknownattributeerror: unknown attribute: student_details_id
what possible solution regarding this? have defined foreign , primary key in models , database, don't know going wrong. tx..!
i think problem foreign key. in studentstatusreport
model defining student_id
column in student_status_reports
table, in studentdetails
model (implicitly) defined student_details_id
(rails guesses association name + _id
unless explicitly define it). error should fixed specifying right foreign_key in parent_model:
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
note student_id
column in student_details
table not used in association, might consider removing create association more clear.
finally, it's thought stick default conventions in rails (integer autoincrement primary keys named id
, singular model names). can't... :s
ruby-on-rails-3 activerecord foreign-keys associations has-many
No comments:
Post a Comment