所以请想象一下汽车预订的表格,表格包含一些客户信息(姓名,年龄,城市......)以及预订信息(start_date,end_date ......)。 显然,我需要首先根据信息以及与创建的客户端相关的预留以相同的形式创建客户端:
class Client < ActiveRecord::Base
has_many :reservations
end
class Reservation < ActiveRecord::Base
belongs_to :client
belongs_to :voiture
end
这是我到现在为止做的事情(糟糕的方式)。 保留信息以f.text_field开头,客户端信息仅以text_field开头(非常糟糕的方式是:()
<%= form_for([@voiture, @voiture.reservations.new]) do |f| %>
<div class="row">
<div class="col-md-12 price_tag">
<span><%= @voiture.price %>Dhs</span>
<span class="pull-right">Par jour</span>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>Nom</label>
<%= text_field :nom, readonly: 'true', placeholder: 'Nom', class: 'form-control' %>
</div>
<div class="col-md-6">
<label>Prenom</label>
<%= text_field :prenom, readonly: 'true', placeholder: 'Prenom', class: 'form-control', disabled: 'true' %>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>CIN</label>
<%= text_field :cin, readonly: 'true', placeholder: 'CIN', class: 'form-control' %>
</div>
<div class="col-md-6">
<label>Age</label>
<%= text_field :age, readonly: 'true', placeholder: 'Age', class: 'form-control', disabled: 'true' %>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>Ville</label>
<%= text_field :ville, readonly: 'true', placeholder: 'Ville', class: 'form-control' %>
</div>
<div class="col-md-6">
<label>Télephone</label>
<%= text_field :telephone, readonly: 'true', placeholder: 'Telephone', class: 'form-control', disabled: 'true' %>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>Email</label>
<%= text_field :email, readonly: 'true', placeholder: 'Email', class: 'form-control' %>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>Check In</label>
<%= f.text_field :start_date, readonly: 'true', placeholder: 'Start Date', class: 'form-control' %>
</div>
<div class="col-md-6">
<label>Check Out</label>
<%= f.text_field :end_date, readonly: 'true', placeholder: 'End Date', class: 'form-control', disabled: 'true' %>
</div>
</div>
<%= f.hidden_field :voiture_id, value: @voiture.id %>
<%= f.hidden_field :prix, value: @voiture.prix %>
<%= f.hidden_field :total, id: 'reservation_total' %>
<%= f.submit "Book Now", id:"btn_book", class: "btn btn-primary wide", disabled: 'true' %>
控制器:
class ReservationsController < ApplicationController
before_action :authenticate_user!
def create
@client = Client.create(client_params)
@reservation = @client.reservations.create(reservation_params)
redirect_to @reservation.voiture, notice: "Votre reservation a bien ete cree"
end
def reservation_params
params.require(:reservation).permit(:start_date, :end_date, :prix, :total, :voiture_id)
end
def client_params
params.permit(:nom, :prenom, :cin, :age, :ville, :telephone, :email)
end
end
我确信这样做有一个干净利落的方式...... 谢谢!
答案 0 :(得分:0)
我会查看嵌套属性以获得良好的清洁解决方案,这里是文档链接http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
还有一个宝石可以为您简化它 https://github.com/ryanb/nested_form