Reputation: 103
If I have a user and article model with an association has_many :articles and belongs_to :user, I would write user.articles.new to create a new article object with the correct user_id .
So my question is about a model with many belongs_to relations:
class Ownership < ActiveRecord::Base
attr_accessible :right_read, :right_create, :right_update, :right_delete
belongs_to :element
belongs_to :user
belongs_to :ownership_type
end
Is there a solution to create an object Ownership with the 3 IDs completed (element_id, user_id, ownership_type_id) ?
And is it dangerous to write this IDs in the "attr_accessible" ?
Thank you.
Upvotes: 0
Views: 69
Reputation: 29281
The new
method accepts a hash where the keys match the attributes in the model. This should work just fine:
Ownership.new(:element_id => element_id, :user_id => user_id, :ownership_type_id => ownership_type_id)
Reference: http://apidock.com/rails/ActiveRecord/Base/new/class
Also, no, it's not dangerous to include those attributes under attr_accessible
-- actually, that's the only way you'll be able to directly write to them using new
or update_attributes
.
Upvotes: 1