我有一个作者拥有并且属于多本书的场景,反之亦然。在instructions之后建立one-to-many
关系中的关联可以正常工作,但是当介绍many-to-many
关系时,只要尝试创建或更新我的书籍模型,就会收到此错误消息。与Rails中的公共活动使用多对多关系
undefined method `author' for #<Book:0x007fb91ae56a70>
至于设立的作者是如何选择一本书我使用令牌输入提供的代码railscast here有一些改变。
class Author < ActiveRecord::Base
has_many :authorships
has_many :books, through: :authorships
def self.tokens(query)
authors = where("name like ?", "%#{query}%")
if authors.empty?
[{id: "<<<#{query}>>>", name: "Add New Author: \"#{query}\""}]
else
authors
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) {create!(name: $1).id}
tokens.split(',')
end
end
class Book < ActiveRecord::Base
attr_reader :author_tokens
include PublicActivity::Model
tracked owner: :author
has_many :authorships
has_many :authors, through: :authorships
def author_tokens=(ids)
self.author_ids = Author.ids_from_tokens(ids)
end
end
表单视图
<%= form_for(@book) do |f| %>
...
<div class="field">
<%= f.text_field :author_tokens, label: 'Author', input_html: {"data-pre" => @book.authors.to_json} %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
@MohammadAbuShady任何想法如何根据之前讨论的一对多来完成? – 2015-04-02 17:42:54
当你把它改成'has_many:authors'你失去了'author'方法并且得到了'authors'方法 – 2015-04-02 20:07:34
@MohammadAbuShady完美无缺。 Piotrek提供的解决方案展示了如何在proc中选择一个作者,但目标是让他们全部完成。这可能在这种特殊情况下做到吗? – 2015-04-02 21:17:44