我有一个图书馆应用程序,其中一个人可以借阅一本书,无论是老师还是学生。在我的借阅形式中,模型都有他们的选择我想只需要一个选择并控制通过另一个虚拟选择,有两个选项老师和学生通过选择其中一个动态加载数据形成一个表。
<%= form_for(@borrow) do |f| %>
<% if @borrow.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@borrow.errors.count, "error") %> prohibited this borrow from being saved:</h2>
<ul>
<% @borrow.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :book_issue_date %><br>
<%= f.date_select :book_issue_date %>
</div>
<div class="field">
<%= f.label :book_return_date %><br>
<%= f.date_select :book_return_date %>
</div>
<div class="field">
<%= f.label :book_id %><br>
<%= f.collection_select(:book_id, Book.all, :id, :book_title) %>
</div>
<div class="field">
<%= f.label :student_id %><br>
<%= f.collection_select(:student_id, Student.all, :id, :student_name) %>
</div>
<div class="field">
<%= f.label :teacher_id %><br>
<%= f.collection_select(:teacher_id, Teacher.all, :id, :teacher_name) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:0)
使用多态关系如下
class Book < ActiveRecord::Base
belongs_to :borrowable, polymorphic: true
end
class Teacher < ActiveRecord::Base
has_many :books, as: :borrowable
end
class Students < ActiveRecord::Base
has_many :books, as: :borrowable
end
现在你在书上有单一选择
@book.borrowable_type
会给你老师或学生,你可以在书中有其他属性,即book_issue_date,book_return_date等