【问题标题】:Rails 4: prepopulate form with param from URLRails 4:使用来自 URL 的参数预填充表单
【发布时间】:2015-11-19 18:19:07
【问题描述】:

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

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

一个日历has_many 帖子和一个帖子belong_to 一个日历。

通过Posts#New 视图创建一个新的帖子对象,格式如下:

<%= 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 传递时,我如何这样做?

【问题讨论】:

    标签: ruby-on-rails forms ruby-on-rails-4 parameter-passing


    【解决方案1】:

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

    【讨论】:

    • +1 还想注意条件可能会被删除:@post = @calendar.posts.build(date: params[:date]) 应该适用于这两种情况,如果查询字符串中没有提供日期,它只会将日期设置为 nil(这可能是默认值无论如何价值)
    【解决方案2】:

    题外话:您可能想使用 link_to 的块语法而不是使用 html_safe?

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

    【讨论】:

    • 当然。在了解您推荐的内容之前,我已经构建了此页面,并且尚未更新我的代码。感谢您的关注。
    猜你喜欢
    • 2014-08-16
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 2013-04-01
    相关资源
    最近更新 更多