简体   繁体   中英

models in attr_accessible

There are numerous examples about relationships between models in Rails but they all seem to leave out the attr_accessible part of the model.

I'm looking for some best practices around the attr_accessible and I'm finding conflicting advice. Can/should I:

-- put foreign keys in the attr_accessible?

Class Post
  attr_accessible :name, :user_id

  belongs_to :user
end
Class User
  attr_accessible :first, :last

  has_many :posts
end

-- put complete models in the attr_accessible?

Class Post
  attr_accessible :name, :user

  belongs_to :user
end
Class User
  attr_accessible :first, :last

  has_many :posts
end

Contrary to what Kaeros says, I would actually advise against allowing foreign key fields to be mass-assignable. The reason is that you're then opening up an easy way for someone to send a different user_id when adding a post. This is probably why the examples you're finding are not including foreign keys.

The best way to get around this is to use the collection builder method when adding a new post for a user:

user.posts.create(params[:post])

If you choose to not follow that advice, then it really depends on how you are mass-assigning the values. If your hash contains :user_id , then you should make that accessible, if it contains :user , go with that one. If you are unsure, you could always make both accessible.

Using foreign keys in the attr_accessible seems to be normal and the default option to me. You can see here that the api guide also uses this form.

Adding model names to attr_accessible also worked for me.

I prefer the first option, so i know easily that i am dealing with foreign keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM