I am having a problem getting the page to update. I am completely lost and don't know where to start. My form for does have a :remote=>true
The page initialy l开发者_JS百科oads with a partial wrapped in a div tag called comments. I don't know what to place in the controller or what file to create, or even how to create it, to update the partial when the user clicks submit on the form. Thanks for any help.
Travis,
I'm not sure which action you're trying to perform here exactly, so let's assume you want to create
a new resource.
Let's assume your resource is called Post
If you used rails to generate your PostController
, you'll have a method create
in there.
It may look something like this:
def create
@posts= Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
format.xml { render :xml => @post, :status => :created, :location => @post}
else
format.html { render :action => "new" }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
end
end
end
The key part here is that you'll need a format.js
in the respond_to
block.
When you put a :remote => true
flag on your forms or links, you're telling rails that you want to make the request via Ajax. This results in a data-remote
attribute being placed on your form
or a
element and that is in turn used to tell the unobtrusive Javascript to use Ajax to submit your request.
What you need to make sure is present on your end are the following:
In your controller, make sure there is a format.js
response format listed in the respond_to
block (see example above for html
and xml
.
Second, we're going to create a create.js.erb
file under your app/views/posts
folder. By default, rails will look for a action.format.erb
file that corresponds to your action and format.
In the app/views/posts/create.js.erb
file, you can now place your response javascript that will update your HTML document accordingly. If for example, you had a list of posts and you wanted to add a newly created one to the end of it, you may have something like this:
app/views/something/show.html.erb
<h1>Posts</h1>
<div id="posts">
<%= render @something.posts %>
</div>
<!-- here we will include the :remote => true option, which will add a data-remote attribute to our form -->
<%= form_for Post.new, :remote => true do |f| %>
<%= f.text_area :text %>
<%= f.submit %>
<% end %>
app/views/posts/create.js.erb
// here we're taking our newly created post and appending it to the list shown above
$('#posts').append("<%= escape_javascript(render @post) %>");
Finally, let's assume our post partial is something like this
app/views/posts/_post.html.erb
<p class="post-text"><%= @post.text %></p>
I'm not sure what javascript framework you're using, but here I'm using jQuery. I believe if you're using rails 3.1, jQuery is the default framework used, otherwise you'd have to look at jquery_ujs.
Hope this helps.
精彩评论