【发布时间】:2013-01-14 00:17:38
【问题描述】:
我在 Ruby on 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
现在我的问题是如何在创建文档时将创建文档的用户设置为文档的所有者。该项目还使用 devise、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
我怎样才能正确地做到这一点?我的 Document 控制器的新操作是否适合这样的事情?任何帮助将不胜感激。
【问题讨论】:
-
我不明白你为什么要通过关系进行 has_many。一个文档可以有多个所有者吗?
-
是的,一个文档可以有多个所有者,而不仅仅是一个。
-
那么,您是希望文档创建者被标识为普通所有者之一,还是希望他们被标识为特定所有者/创建者?
-
我想我想以后让创作者和其他所有者一起。我喜欢将创建者添加为第一个所有者,然后在需要时添加新所有者。
标签: ruby-on-rails ruby-on-rails-3 has-many-through