Rails Activerecord Model with 2 foreign keys, neither accessible -
hey have scenario here trying figure out. trying build custom blog in rails requires users signed in leave comment. have 3 models - post, user, , comment. problem comment model. trying have comment belongs_to user , belongs_to post, have many comments. have made post_id , user_id inaccessible not want them tampered (i want comment automatically associated id of post on left, , want user automatically determined via session). problem not sure how can create valid comment. if try add comment doing @blog.comments.build(@attr) ignoring inacessible user, , of course if try build through user ignoring blog.
my guess there better way , might approaching wrong. ideas?
i assume have in comment model:
attr_accessible :content
and when try build comment happens:
@post = post.first @post.comments.build(:user=>current_user) # => warning: can't mass-assign protected attributes: user
so won't work.
if want protect user_id , post_id being overwritten on update, this:
attr_accessible :content, :user_id, :post_id attr_readonly :user_id, :post_id @post = post.first @post.comments.build(:user=>current_user) @post.save! # sets user_id when creating @post.user_id = 37 @post.save! # saves, user_id not changed. no warning logged. @post.update_attributes(:user_id=>37) # same above @post.update_attribute(:user_id,37) # raises activerecord::activerecorderror: user_id marked readonly
but seems overkill, since presumably application not submit form user_id existing comment, , have code own form , post change id.
Comments
Post a Comment