我已經通過Ruby on Rails中兩個模型之間的關聯設置了has_many。設置如下。模型是用戶和文檔,連接模型是所有權。這些模型是這樣定義的:Rails has_many通過在創建時設置屬性
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
現在我的問題是如何設置創建文檔時創建文檔的用戶創建文檔的用戶。該項目還使用設計,cancan和rolify用戶處理。我試圖將其設置在像這樣的Codument控制器的新動作中,但沒有成功
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
我該如何正確地做到這一點?我的文檔控制器的新動作是否正確,就像這樣?任何幫助,將不勝感激。
我不明白你爲什麼要通過關係做一個has_many。一份文件可以有多個所有者? – Preacher
是的文件可以有許多所有者不僅一個。 – ctpfaff
那麼,您是否希望將文檔創建者標識爲常規所有者之一,還是希望將它們標識爲特定所有者/創建者? – Preacher