在Rails中使用与Public Activity gem的多对多关系

时间:2015-04-02 17:41:38

标签: ruby-on-rails activerecord associations railscasts public-activity

我有一个作者拥有并且属于许多书籍的场景,反之亦然。在instructions之后设置one-to-many关系的关联工作正常但是当引入many-to-many关系时,每当我尝试创建或更新我的图书模型时,我都会收到此错误消息。

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

2 个答案:

答案 0 :(得分:0)

您的图书模型中没有author关系。

什么

tracked owner: :author

基本上是在Book实例上调用方法author。您应该尝试:authors

但是!

这不会解决您的问题,因为owner只能是一个。所以你可以这样做:

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

将所有者设置为该图书的第一位作者。

答案 1 :(得分:-2)

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