我的要求 基本上我將書籍添加到數據庫,並且我想將作者存儲在單獨的表格中。所以我有一個表格,這個表格叫做作者,這個表格被桌子所引用。未經許可的參數:作者
我想創建一個用於添加書籍的Rails表單,並且我希望它只是作者,標題,出版商等的簡單表單,並且如果它發現作者已經在authors表中,那麼它應該只需引用該記錄,並且如果它不在authors表中,那麼它應該添加一條新記錄並引用它。
同時存儲值我得到的日誌文件 不允許的參數:作者
Processing by BooksController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8sxeOVMVJucl5nN+kMpSaT1cB1yDPnk5gfKElWPiT5k=", "book"=>{"book_name"=>"life ", "price"=>"20", "author"=>{"author_name"=>"swamy", "title"=>"LIFE", "publisher"=>"cta"}}, "commit"=>"Submit"}
swamy
LIFE
cta
Author Load (1.6ms) SELECT "authors".* FROM "authors" WHERE "authors"."author_name" = 'swamy' AND "authors"."title" = 'LIFE' AND "authors"."publisher" = 'cta' LIMIT 1
(0.6ms) BEGIN
SQL (25.2ms) INSERT INTO "authors" ("author_name", "created_at", "publisher", "title", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["author_name", "swamy"], ["created_at", "2015-07-01 03:53:22.712401"], ["publisher", "cta"], ["title", "LIFE"], ["updated_at", "2015-07-01 03:53:22.712401"]]
(16.8ms) COMMIT
Unpermitted parameters: author
(0.7ms) BEGIN
SQL (1.0ms) INSERT INTO "books" ("Author_id", "book_name", "created_at", "price", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["Author_id", 8], ["book_name", "life "], ["created_at", "2015-07-01 03:53:22.865106"], ["price", 20], ["updated_at", "2015-07-01 03:53:22.865106"]]
(22.4ms) COMMIT
我的代碼 books_Controller
class BooksController < ApplicationController
def new
end
def create
@a=params[:author_name]
puts @a
b=params[:book][:author][:author_name]
puts b
# @c = @b.authors
# @d = @c.author_name
c=params[:book][:author][:title]
d=params[:book][:author][:publisher]
puts c
puts d
@author = Author.find_or_create_by(author_name: b,title: c, publisher: d)
@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,:author_attributes => [:author_name, :title, :publisher])
end
end
模型
class Author < ActiveRecord::Base
end
class Book < ActiveRecord::Base
belongs_to :Author
accepts_nested_attributes_for :Author
# def author_name=(author_name)
# self.author = Author.find_or_create_by_name author_name
#end
end
視圖 books.html。 erb
<%= 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 :author 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 %>
~
喜先生,我是新來的軌道,我知道這看起來簡單,但我無法找到它的解決方案
〜
〜
謝謝先生,但只有書本值存儲在數據庫中,但作者表沒有值,請你解釋如何在檢查後將數據存儲到作者表中你是否已經存在或沒有 – user5065277