将单个字段保存到两个(或多个)表 - Rails 4

时间:2014-03-17 22:04:58

标签: ruby-on-rails ruby-on-rails-4

我有三个模型 - BooksAuthorsBookAuthorsBooksAuthors是多对多的 关系,通过BookAuthors

我想创建一个用于将图书输入数据库的表单,但存在我的问题。我希望Author字段可以做两件事:

  
      
  1. 如果作者表中没有输入名称的作者,请将其保存在那里。
  2.   
  3. 无论1)中发生了什么,它都应该在BookAuthors中创建一个条目,包括book_id,author_id(它是新创建的,或者   在Authors表中找到了现有的一个)和author_type_id。
  4.   

我不知道如何让一个字段引用多个表格。

1 个答案:

答案 0 :(得分:1)

我会这样做:

#app/controllers/books_controller.rb
def new
    @book = Book.new
    @authors = Author.all
end

def create
    @book = Book.new(book_params)
    @book.save
end

private

def book_params
    require(:book).permit(:name, author_id: [], authors_attributes: [:name])
end


#app/views/books/new.html.erb
<%= form_for @book do |f| %>
    <%= f.text_field :name, placeholder: "Name" %>
    <%= f.collection_select :author_id, Author.all, :id, :name, prompt: "Pick an Author"> %>
    <%= f.fields_for :authors do |author| %> 
        <%= author.text_field :name, placeholder: "New Author Name" %>
    <% end %>
<% end %>

<强>过程

这基本上为您提供了一种选择预定义作者或创建新作者的方法

如果创建了新的,系统将保存&amp;引用新作者,而现有作者只会显示现有作者的id

相关问题