ruby on rails - Reset PK number based on association -
i have post
, comments
table.
post
has many comments, , comment
belongs post.
i want have primary keys start @ 1 when create comment post
, can access comments in rest-ful manner, e.g:
/posts/1/comments/1 /posts/1/comments/2 /posts/2/comments/1 /posts/2/comments/2
how can achieve rails 3? using mysql database.
bonus: using sequel
orm; approach compatible sequel, not activerecord, awesome.
well, can't use id this, id primary key here. can add field database table comment_number
, make unique in scope of post:
#migration def change add_column :comments, :comment_number, :integer, null: false add_index :comments, [:post_id, :comment_number], unique: true end #class class comment < activerecord::base belongs_to :post validates :post_id, presence: true validates :comment_number, uniqueness: { scope: :post_id } end
now in place need ensure column populated:
class comment < activerecord::base #... before_create :assign_comment_number private def assign_comment_number self.comment_number = (self.class.max(:comment_number) || 0) + 1 end end
last step tell rails use column instead of id. need override to_param
method:
class comment < activerecord::base #... def to_param comment_number end end
update:
one more thing, useful make field read-only:
class comment < activerecord::base attr_readonly :comment_id end
also after rethinking having uniqueness validation on comment_number
makes little sense having assigned after validations run. should rid of , rely on database index.
even having validation, there still possible condition race. override save method handle constraint validation exception retry couple of time ensure won't break application flow. topic question.
Comments
Post a Comment