基本上我将书籍添加到数据库中,我想将作者存储在一个单独的表中。所以我有一个叫做作者的表,由表格书引用。
我想创建一个用于添加图书的rails表单,我希望它只是作者,标题,发布商等的简单表单,如果它发现作者已经在authors表中,那么它应该只引用该记录,如果它不在authors表中,那么它应该添加一条新记录并引用它。
它正在工作,但值不存储到authors表中? 在检查表中的作者姓名时,我得到nil参数:
{"utf8"=>"✓", "authenticity_token"=>"/Tk87vLoJx+/EgPGVEa7x59IeGMGLikknBMcMTw90oo=", "book"=>{"book_name"=>"y", "price"=>"1", "authors"=>{"author_name"=>"b", "title"=>"k", "publisher"=>"s"}}, "commit"=>"Submit"}
Author Load (1.9ms) SELECT "authors".* FROM "authors" WHERE "authors"."author_name" IS NULL LIMIT 1
Unpermitted parameters: authors
params[:authors_name] in method Author.find_or_create_by() value is nil
but book column values are added to books table and author table id is only apears in author table
使用参考
创建模型 rails generate model Author author_name:string{15} title:string{15} publisher:string{15}
rails generate model Book book_name:string{15} price:integer Author:references
书籍 - 控制器
class BooksController < ApplicationController
def new
end
def create
# Client.find_or_create_by(first_name: 'Andy')
@author = Author.find_or_create_by(:author_name => params[:author_name])
@book = Book.new(books_params)
@book.Author = @author
@book.save
redirect_to root_url
end
private
def books_params
params.require(:book).permit(:book_name, :price,:address => [:author_name, :title, :publisher])
end
end
型号代码
class Book < ActiveRecord::Base
belongs_to :Author
accepts_nested_attributes_for :Author
end
class Author < ActiveRecord::Base
end
book.html
<%= form_for Book.new do |f| %>
<p>
<%= f.label :book_name %><br />
<%= f.text_field :book_name %>
</p>
<p>
<%= f.label :price %><br />
<%= f.text_field :price %>
</p>
<%= f.fields_for :authors do |b| %>
<p>
<%= b.label :author_name%><br />
<%= b.text_field :author_name %>
</p>
<p>
<%= b.label :title%><br />
<%= b.text_field :title %>
</p>
<p>
<%= b.label :publisher%><br />
<%= b.text_field :publisher%>
</p>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
~
我的问题是
2如何在authors表中保存authors列值?