ctpfaff
ctpfaff

Reputation: 59

Rails has_many through set an attribute on creation

I have setup a has_many through association between two models in Ruby on Rails. The setup is as follows. The models are User and Document, the join model is Ownership. The models are defined like this:

class Ownership < ActiveRecord::Base
  attr_accessible :document_id, :user_id 
  belongs_to :user
  belongs_to :document 
end

class User < ActiveRecord::Base
  has_many :ownerships
  has_many :documents, :through => :ownerships
end

class Document < ActiveRecord::Base
  has_many :ownerships
  has_many :users, :as => :owners, :through => :ownerships
end

Now my question is how to set the user that creates a document as the owner of the document when it gets created. The project also uses devise, cancan and rolify for user handling. I tried to set it in the new action of the Codument controller like this but with no successs

def new 
  @document = Document.new

  @document.users = current_user

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @document }
  end 
end 

How can I do this properly? And is the new action of my Document controller the right place at all to something like this? Any help would be appreciated.

Upvotes: 0

Views: 948

Answers (1)

Dennis Hackethal
Dennis Hackethal

Reputation: 14275

First off, you need to assign the user in the controller's create method. Second, since a document can have many users, @document.users is an enumerable and cannot simply be assigned a single user by doing

@document.users = current_user

You can rather do:

@document.owners << current_user

in the create method. Note that as per your model the document has owners rather than users.

Change

has_many :users, :as => :owners, :through => :ownerships

to

has_many :owners, source: :user, through: :ownerships, foreign_key: :user_id

in your document model.

This stores the current user when the document is saved.

Upvotes: 1

Related Questions