簡體   English   中英

Rails 4:使用URL中的參數預填充表單

[英]Rails 4: prepopulate form with param from URL

在我的Rails 4應用程序中,我有一個使用shallow routesCalendarPost模型:

resources :calendars do
  resources :posts, shallow: true
end

日歷has_many帖子和一個帖子belong_to於日歷。

通過Posts#New視圖以以下形式創建一個新的post對象:

<%= form_for [@calendar, @calendar.posts.build], html: { multipart: true } do |f| %>

  <div class="field">
    <%= f.label :date, "DATE & TIME" %>
    <%= f.datetime_select :date %>
  </div>

  [...] # Truncated for brivety

  <div class="actions">
    <%= f.submit @post.new_record? ? "CREATE POST" : "UPDATE POST", :id => :post_submit %>
  </div>

<% end %>

在某些情況下(但不是全部),我想用通過URL傳遞的參數預填充表單的日期字段。

我已經能夠通過帶有以下鏈接的URL傳遞日期:

<%= link_to '<i class="glyphicon glyphicon-plus-sign"></i>'.html_safe, new_calendar_post_path(@calendar, date: date) %>

該鏈接為我提供了以下類型的URL:

http://localhost:3000/calendars/6/posts/new?date=2015-11-12

從那里,如何預填充表格?

最重要的是, 只有通過URL傳遞日期時,才可以這樣做嗎?

您應該在new操作中在Post控制器中預填充新的Post數據

class PostsController << ApplicationController
  ...
  def new
    if (date = params['date']).present?
      @post = @calendar.posts.build(date: date)
    else
      @post = @calendar.posts.build
    end
  end
  ...
end

在您看來

<%= form_for [@calendar, @post], html: { multipart: true } do |f| %>

  <div class="field">
    <%= f.label :date, "DATE & TIME" %>
    <%= f.datetime_select :date %>
  </div>

  [...] # Truncated for brivety

  <div class="actions">
    <%= f.submit @post.new_record? ? "CREATE POST" : "UPDATE POST", :id => :post_submit %>
  </div>

<% end %>

主題外:您可能想對link_to使用塊語法而不是html_safe?

<%= link_to new_calendar_post_path(@calendar, date: date) do %>
  <i class="glyphicon glyphicon-plus-sign"></i>
<% end %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM