Rails 4:使用来自 URL 的参数预填充表单

Rails 4: prepopulate form with param from URL

在我的 Rails 4 应用程序中,我有一个 Calendar 和一个 Post 模型,使用 shallow routes:

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

日历has_manypost和postbelong_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:

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

这个 link 给了我一个 URL 以下类型:

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

如何从那里预填充表格?

最重要的是,当日期通过 URL?

时,我如何才能做到 ONLY

您应该在 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 %>