【发布时间】:2021-01-08 22:51:54
【问题描述】:
在我的应用程序中,我有一个会议和一个联系人模型。 我已经使用 selectize 设置了一个 jquery 函数,它允许我直接在我的会议/新表单中创建一个新联系人。 为此,我在 ajax 中使用 POST 请求,并在 contacts_controller.rb 中为我的 create 方法渲染 json:
def create
@contact = Contact.new(contact_params)
@user = current_user
@contact.user = @user
if @contact.save!
render json: @contact, except: :avatar
else
render json: { errors: @contact.errors.full_message }
end
end
这种行为在我的会议/创建方法中是完美的,因为它允许我使用模态创建一个新联系人并在我的表单中获取我的函数的回调以显示新的联系人姓名。 这是我的会议/新观点:
*view : meeting/new*
<%= simple_form_for(@meeting) do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.input :start_date %>
<%= f.input :end_date %>
<%= f.association :contact, collection: Contact.all.pluck(:fullname, :id), input_html: { class: "select-contact" } %>
<%= f.submit 'Enregistrer un nouvel rendez-vous', class:'btn btn-secondary' %>
<% end %>
<div class="modal fade contact-modal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="mySmallModalLabel">Ajouter un contact</h4>
</div>
<div class="modal-body">
<%= simple_form_for Contact.new, remote: true do |f| %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :fullname %>
<%= f.submit 'Ajouter un nouveau contact', class:'btn btn-primary' %>
<% end %>
</div>
</div>
</div>
</div>
我的问题是我还想通过我的联系人/新视图创建一个新联系人。但是在创建这个联系人之后,我会重定向到我的索引视图。
*view : contact/new*
<%= simple_form_for [ @user, @contact ] do |f| %>
<%= f.input :avatar, as: :file %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :fullname %>
<%= f.input :email %>
<%= f.input :phone_number %>
<%= f.input :tag_list %>
<%= f.input :birthdate, as: :string, type: :text, input_html: {class: "datepicker", id: "birthdate"} %>
<%# raise %>
<%= f.submit %>
<% end %>
由于我在联系人控制器中的 create 方法,当我的联系人被保存时它会触发渲染 json,但没有重定向
当我通过我的会议/新视图创建新联系人时,我将呈现 json 而不进行重定向。当我在联系人/新视图中创建新联系人时,我会在创建后重定向到我的联系人/索引视图。 在这两种情况下,我都需要发布一个 ajax 请求来存储一些数据。
有人知道我该怎么做吗?
非常感谢
【问题讨论】:
标签: jquery ruby-on-rails json redirect rendering