【问题标题】:Rails has_many through set an attribute on creationRails has_many 通过在创建时设置属性
【发布时间】: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


【解决方案1】:

首先,您需要在控制器的 create 方法中分配用户。其次,由于一个文档可以有多个用户,@document.users 是一个可枚举的,不能简单地通过这样做来分配单个用户

@document.users = current_user

你可以这样做:

@document.owners << current_user

在创建方法中。请注意,根据您的模型,文档有所有者而不是用户。

改变

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

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

在您的文档模型中。

保存文档时存储当前用户。

【讨论】:

  • 谢谢。它在我执行 (at)document.users :owners 的别名设置有问题?
  • 我不确定 - 你试过has_many :owners, class_name: :user, through: :ownerships吗?
  • 嗯,没有。但我现在测试了它,它也不起作用。它告诉我:在模型所有权中找不到源关联:所有者或:所有者。试试“has_many”。
  • 试试has_many :owners, class_name: :user, through: :ownerships, foreign_key: :user_id
  • 不幸的是,这也没有成功。这有相同的错误消息。
猜你喜欢
  • 2018-02-28
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 1970-01-01
  • 2011-03-06
相关资源
最近更新 更多