Thibaud Clement
Thibaud Clement

Reputation: 6907

Rails 4: prepopulate form with param from URL

In my Rails 4 app, I have a Calendar and a Post models, using shallow routes:

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

A calendar has_many post and a post belong_to a calendar.

A new post object is created via the Posts#New view, with the following form:

<%= 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 %>

In certain cases — but not all — I want to prepopulate the date field of the form with the params passed through the URL.

I have been able to pass a date through the URL with the following link:

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

This link gives me a URL of the following kind:

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

From there, how can I prepopulate the form?

And most importantly, how can I do so ONLY when a date is passed through the URL?

Upvotes: 2

Views: 1841

Answers (2)

house9
house9

Reputation: 20624

Off topic: you might want to use the block syntax for link_to instead of using html_safe?

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

Upvotes: 1

Long Nguyen
Long Nguyen

Reputation: 11275

You should prepopulate new Post data in Post controller on new action

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

And in your view

<%= 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 %>

Upvotes: 4

Related Questions