1

我有一个作者模型

class Author
  include Mongoid::Document
  field :name

end

在我的文章表格中,我想带上所有作者

 <div class="field">
    <%= f.label :author_tokens, "Authors" %><br />
    <%= f.text_field :author_tokens, "data-pre"=> @article.authors.map(&:attributes).to_json %>
  </div>

这是工作。所有作者的名字都可以看到。现在我想提交所有作者姓名,我在作者中单击。我的文章模型应该是什么?我很困惑。当我发布时在这里

{"utf8"=>"✓",
 "authenticity_token"=>"bE0PpLx+qBUJqIavfvpDOjzrhIHFku+IrgjnU0OLOC8=",
 "article"=>{"name"=>"ram",
 "published_on(1i)"=>"2012",
 "published_on(2i)"=>"8",
 "published_on(3i)"=>"20",
 "author_tokens"=>"",
 "content"=>"fdsfds"},
 "commit"=>"Create Article"}

author_tokens 字段为空。我有我的文章模型

class Article

  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes
  field :name
  field :content
  field :author_tokens
  field :token_inputs
 field :published_on, :type => Date 
 validates_presence_of :name,:content

has_many :authors
 attr_reader :author_tokens

 def author_tokens=(ids)
 self.author_ids =ids.split
 end

end

我的文章模型应该是什么,以便我可以将所有输入的作者标记名称保存在我的文章集合中?

4

1 回答 1

1

在文章模型上,尝试删除:

field :author_tokens

并添加:

attr_accessible :author_tokens

此外,不确定该token_inputs字段的使用位置。也许没必要?

编辑:

我之前忽略了这一点,但是你需要has_and_belongs_to_many在关系的两边才能让它按照你想要的方式工作,所以:

Class Author
  has_and_belongs_to_many :articles
  ...
end

和:

Class Article
  has_and_belongs_to_many :authors
  # has_many :authors <- Remove this
  ...
end

为了澄清我原来的解释:

1)您编写的 setter 方法author_tokensattr_reader : author_tokens都很好,但如果您在控制器中使用质量分配(可能),您需要author_tokens使用attr_accessible :author_tokens. 如果您尚未明确设置任何其他内容,Mongoid 可能会自动执行此操作attr_accessible,具体取决于您使用的版本。

2)您不需要该field :author_tokens行,因为它是通过您编写的 setter 和attr_reader调用访问的虚拟属性。您实际上并不想将用户传入的值存储author_tokens在数据库中,而是希望设置器为您将这些值放入author_ids字段中。

3)has_and_belongs_to_many :authors调用将author_ids在文档中为您创建字段。

4) 假设您使用的是此处显示的模式,那么在使用 Mongoid 而不是 ActiveRecord 时,前端实现应该没有什么不同。

于 2012-08-21T22:49:04.820 回答