Joel Blum
Joel Blum

Reputation: 7888

Rails render forms in same page

This is my scenario I have a Stories controller that has a form to create a new Post :

stories.show.erb
...
<%=link_to("Create new post",new_story_post_path(@post))%>

This new post is generated by Posts controller

posts\new.erb
<%= form_for [@story,@post] do |f|%>

I want to break away from the traditional behavior - I want the new post form to be displayed inside the same 'story' page and NOT have a full page reload and appearing in a new page .

What's the best way to do this in rails ?

Upvotes: 0

Views: 926

Answers (2)

Mandeep
Mandeep

Reputation: 9173

I think in your case it'll be best if you add the form in your stories show view and make it as hidden and then when a user clicks on the link to create a new post you can show them your form.

def show
  @story = Story.find(params[:id])
  @post = @story.posts.build # assuming stories have many posts
end

#show.html.erb
...
<%=link_to "Create a new Post", "#", id: "post-link"%>

<%= form_for [@story,@post], html: {id: "new-post"} do |f|%>
  // form fields
<% end %>

#some_file.js
$(document).on("click","#post-link",function(){
  $("#new-post").show();
});

#some.css.scss
#new-post{display:none;}

Upvotes: 1

Igor Guzak
Igor Guzak

Reputation: 2165

you could write:

<%= form_for [@story,@post], remote: true do |f|%>

in create.js.erb you could write

$('#post_block').html("<%= render 'your partial with posts' %>")

Upvotes: 0

Related Questions