在Rails中使用与公共活动gem的多对多关系



我有一个场景,一个作者拥有并属于许多书,反之亦然。按照在one-to-many关系中设置关联的说明操作很好,但当引入many-to-many关系时,每当我尝试创建或更新我的图书模型时,我都会收到此错误消息。

undefined method `author' for #<Book:0x007fb91ae56a70>

至于设置如何为一本书选择作者,我在这里使用令牌输入railscast提供的代码,并进行了一些修改。

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 %>

Book模型中没有author关系。

什么

tracked owner: :author

所做的基本上是在Book实例上调用方法author。你应该试试:authors

但是

这不会解决你的问题,因为owner只能是一个。所以你可以做一些类似的事情:

tracked owner: proc {|_, book| book.authors.first }

将所有者设定为该书的第一作者。

class Author < ActiveRecord::Base
  has_many :author_books, inverse_of: :author, dependent: :destroy
  accepts_nested_attributes_for :author_books
  has_many :books, through: :author_books
end
class Book < ActiveRecord::Base
  has_many :author_books, inverse_of: :book, dependent: :destroy
  accepts_nested_attributes_for :author_books
  has_many :authors, through: :author_books
end
class AuthorBook < ActiveRecord::Base
  validates_presence_of :book, :author
end

===============视图================

<%= form_for @book do |f| %>
  <%= f.text_field :title %>
  <%= f.fields_for :author_books do |f2| %>
    <%# will look through all author_books in the form builder.. %>
    <%= f2.fields_for :author do |f3| %>
      <%= f3.text_field :name %>
    <% end %>
  <% end %>
<% end %>

相关内容

  • 没有找到相关文章

最新更新