我正在创建一个Rails库应用,其中一种类型的has_many书籍和一类belongs_to的书籍。我需要使用表单对象,因为我的数据模型最终将具有多个多对多的关系,并且因为我想学习如何使用表单对象。我已经基于Rails Cast#416表单对象创建了表单对象。我的表单,表单对象,模型和 Controller 似乎都可以正常工作。创建了新书并将它们与流派相关联,但是它们都是流派“流派”。我正在使用find_or_create_by。我认为问题出在book_form.rb上,但@genre ||= Genre.find_by(name: :name)实际上并未从表单中传递流派信息。我的相关代码如下:

样板书.rb

class Book < ActiveRecord::Base
  belongs_to :genre
  before_save :convert_isbn
.
.
.
end

型号genre.rb
class Genre < ActiveRecord::Base
  has_many :books, dependent: :destroy
  validates_associated :books
end

book_form.rb
class BookForm
  include ActiveModel::Model

  def self.model_name
    ActiveModel::Name.new(self, nil, "Book")
  end
.
.
.
  validates :name, presence: true

  delegate :name, to: :genre
  delegate :title, :year, :pages, :isbn, :summary, :volume_a, :volume_b, to: :book

  def genre
    @genre ||= Genre.find_by(name: :name)
  end

  def book
    @book ||= genre.books.build
  end

  def submit(params)
    genre.attributes = params.slice(:name).permit(:name)
    book.attributes = params.slice(:title, :year, :pages, :isbn, :summary, :volume_a,:volume_b).permit(:title, :year, :pages, :isbn, :summary, :volume_a,:volume_b)
    if valid?
      genre.save!
      book.save!
      true
    else
      false
    end
  end
end

books_controller.rb
class BooksController < ApplicationController
  before_action :admin_user, only: [:new, :edit, :destroy]

  def new
    @book_form = BookForm.new
    @genres = Genre.all
  end

  def create
    @book_form = BookForm.new
    @genres = Genre.all
    if @book_form.submit(params[:book])
      flash[:success] = "You've added a new book to the library!"
      redirect_to @book_form
    else
      render 'new'
    end
  end

查看new.html.erb
<%= form_for @book_form do |f| %>
  <%=render 'shared/error_messages', object: f.object %>

  <%= f.label :title %>
  <%= f.text_field :title, class: 'form-control' %>
  .
  .
  .
  <%= f.label :genre %><br>

  <%= collection_select(:genre, :name, Genre.all, :name, :name) %>
  <br>
  <br>
  <%= f.submit "Add book to library", class: "btn btn-primary" %>
<% end %>

使用Pry gem,我可以从服务器上获得这本书:
Started POST "/books" for ::1 at 2016-02-22 14:19:20 -0700
Processing by BooksController#create as HTML
  Parameters: {"utf8"=>"✓",     "authenticity_token"=>"bPusgyl9n+p07eQsEAe9CpSsithtkg33HMifj8KTsidv3GDLuhjibOC7d2mm5boC4w7ZUne64R4n4OMQotDE4g==",
               "book"=>{"title"=>"test",
               "year"=>"2016",
               "pages"=>"222",
               "isbn"=>"9780-xx-xx-xx",
               "summary"=>"fake summary",
               "volume_a"=>"1",
               "volume_b"=>"2"},
               "genre"=>{"name"=>"Mystery"},
               "commit"=>"Add book to library"}

From: /home/nathaniel/rails_apps/allredlib/app/forms/book_form.rb @ line 38 BookForm#submit:

    37: def submit(params)
 => 38:   binding.pry
    39:   genre.attributes = params.slice(:name).permit(:name)
    40:   book.attributes = params.slice(:title, :year, :pages, :isbn, :summary, :volume_a,:volume_b).permit(:title, :year, :pages, :isbn, :summary, :volume_a,:volume_b)
    41:   if valid?
    42:     genre.save!
    43:     book.save!
    44:     true
    45:   else
    46:     false
    47:   end
    48: end

因此,书籍体裁正在传递给参数,但是我在书籍形式中访问错误的方式。如果我注释掉binding.pry,则表单会创建一本类型为“名称”的新书,而不是像我希望的那样,类型为“神秘”的书。

当我在使用binding.pry的同时将@genre键入rails时,我得到了
[1] pry(#<BookForm>)> @genre
=> #<Genre:0x007f19554e1220
 id: 20,
 name: "name",
 book_id: nil,
 created_at: Thu, 25 Feb 2016 20:28:45 UTC +00:00,
 updated_at: Thu, 25 Feb 2016 20:28:45 UTC +00:00>

最新的binding.pry结果
27:def类型
=> 28:binding.pry
29:@genre || = Genre.find_or_initialize_by(name::name)
30:#@ genre || = Genre.find_or_initialize_by(名称:params [:genre] [:name])
31:结束

最佳答案

如果要按名称查找流派,则需要在方法的选项哈希中传入name属性。

def genre
  @genre ||= Genre.find_or_create_by(name: :name)
end

更新

改变
genre.attributes = params.slice(:name).permit(:name)


genre.attributes = { :name => params[:genre][:name] }

还要在genre.save之前和之后抛出binding.pry!并查看如果您键入@genre会得到什么,因为您的流派方法应该已经创建了该实例变量,您只需将其参数与接受哈希的genre.attributes一起发送给该实例变量即可。

我会在书本参数上考虑相同的内容,但是如果slice可以正常工作的话。

另外,由于您是在表单 View 中调用Genre.all的,因此您可能不需要在 Controller 操作中执行此操作,但是如果这样做,则请考虑在表单 View @genres中使用对象collection_select,因为您正在制作对模型都提出了两次要求。
@genres = Genre.all

关于ruby-on-rails - 将Rails find_or_create_by与表单对象一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35352937/

10-16 00:45