マイクロポストを送信して、ページをリロードせずにページの上部に表示しようとしていますが、うまく動作しません。説明と解決策は大歓迎です。
多くのマイクロポストを持つユーザーがいます
解決
https://github.com/sunwooz/fasttwitter/pull/1
Here is a working implementation let me go thru the changes really quick
fasttwitter/app/views/layouts/application.html.erb
Since rails 3.1 you should use "application" instead of "defaults" apparently this was the main problem, because it generated an error stopped the remote => true from working
fasttwitter/app/views/microposts/create.js.coffee
There is no need for this file. rails is going to check for a .erb file not a .coffee
fasttwitter/app/views/microposts/create.js.erb
I had some problems with the partial rendering, but it is working with the html you posted on Stackoverflow
これはshow.html.erb(user)です
<h1><%= @user.email %></h1>
<%= form_for [@user, @micropost], :remote => true do |f| %>
<h1>What are you thinking?</h1><br/>
<%= f.text_field :content, :class => 'micropostfield', :placeholder => 'Press ENTER to submit' %><br/>
<%= f.submit %>
<% end %>
<div id="microposts">
<%= render @user.microposts.reverse %>
</div>
_micropost.html.erb 部分
<%= div_for micropost do %>
<h3><%= micropost.user.email %></h2> <h4>Posted <%= time_ago_in_words(micropost.created_at) %> ago</h3>
<p>
<%= micropost.content %>
</p>
<p>
<%= link_to "Edit", edit_user_micropost_path(micropost) %>
<%= link_to "Destroy", user_micropost_path(micropost), :method => :delete, :class => :destroy %>
</p>
Microposts.js
$(document).ready(function() {
$('#new_micropost').submit(function(evt){
var text = $('#micropost_content').val();
var url = $('#new_micropost').attr('action');
$.ajax({
url: url,
type: 'POST',
data: { micropost: { content: text }},
dataType: "JSON",
success: function(data){
$('#microposts').prepend('<div class="micropost"><h3>' + data.@user.email + '</h3><h4>Posted On: ' + data.created_at + '</h4><p>' + data.content + '</p></div>');
};
});
evt.preventDefault();
});
});
マイクロポスト作成アクション
def create
@user = User.find(params[:user_id])
@micropost = @user.microposts.build(params[:micropost])
respond_to do |format|
if @micropost.save
format.html { redirect_to(@user) }
format.xml { render :xml => @user, :status => :created, :location => @user }
format.js
else
format.html { redirect_to(@user) }
format.xml { render :xml => @micropost.errors }
format.js { render :json => @micropost.errors }
end
end
end