at.
at.

Reputation: 52590

Any difference between :model and :model_id in attr_accessible for Rails/ActiveRecord?

When I create a scaffold and I need to have a belongs_to relation to another model, I add a field called model_id (replacing model with that model's name):

rails generate scaffold Grade user_id:integer subject_id:integer letter:string

Then in the above Grade model, I might add:

belongs_to :user
belongs_to :subject

Rails automatically adds user_id and subject_id to the list of attr_accessible fields. Do I do any harm by also adding :user and :subject to the list of attr_accessible fields so that I can mass assign using those as well?

Upvotes: 3

Views: 531

Answers (2)

Stanislav Mekhonoshin
Stanislav Mekhonoshin

Reputation: 4386

I think it doesn't hurt you, but will bring a kind of mess in your code

Upvotes: 0

Peter Brown
Peter Brown

Reputation: 51717

attr_accessible is intended to protect against mass-assignment attacks that come from data that is externally sent to your application. In most cases you're probably doing things like this in your create & update actions:

@model = Model.new(params[:model])
or
@model.update_attributes(params[:model])

You should ask yourself why you'd have one form that uses subject_id and another that uses subject. The only real harm here is inconsistency, which can actually be pretty detrimental to large projects. If you follow the convention that all forms will use the actual database column (subject_id), then you'll save yourself some headache in the future when you can't remember out why you did it two different ways.

If you're updating attributes through the console, you can either use update_attributes(params[:model], without_protection: true) or a gem I wrote called sudo_attributes which lets you do sudo_update_attributes(params[:model]).

Upvotes: 2

Related Questions