ruby on rails - models in attr_accessible -
there numerous examples relationships between models in rails seem leave out attr_accessible part of model.
i'm looking best practices around attr_accessible , i'm finding conflicting advice. can/should i:
-- set foreign keys in attr_accessible?
class post attr_accessible :name, :user_id belongs_to :user end class user attr_accessible :first, :last has_many :posts end
-- set finish models in attr_accessible?
class post attr_accessible :name, :user belongs_to :user end class user attr_accessible :first, :last has_many :posts end
contrary kaeros says, advise against allowing foreign key fields mass-assignable. reason you're opening easy way send different user_id when adding post. why examples you're finding not including foreign keys.
the best way around utilize collection builder method when adding new post user:
user.posts.create(params[:post])
if take not follow advice, depends on how mass-assigning values. if hash contains :user_id
, should create accessible, if contains :user
, go one. if unsure, create both accessible.
ruby-on-rails rails-activerecord
No comments:
Post a Comment