我有一个创建Tweet
的表单。用户的所有推文都以无序列表呈现。当用户创建Tweet
时,我希望将其附加到列表中,而无需使用AJAX重新加载页面。
这些代码有什么问题?有什么想让它工作/更好?
show.htm.erb
<div class="col-md-6 col-md-offset-3 cat-tweet">
<h3>Tweets (<%= @cat.tweets.count %>)</h3>
<% if logged_in? && current_user?(@cat.user) %>
<%= render 'shared/tweet_form' %>
<% end %>
<% if @cat.tweets.any? %>
<ol class="tweets" id="tweets">
<%= render @tweets %>
</ol>
<%= will_paginate @tweets %>
<% end %>
</div>
_tweet_form.html.erb
<%= form_for(Tweet.create, remote:true) do |f| %>
<div class="field">
<%= f.text_area :content, placeholder: "Compose a new tweet...", id: "tweet-text-area" %>
</div>
<%= hidden_field_tag :cat_id, @cat.id %>
<%= f.submit "Tweet that!", class: "btn btn-primary",id: "tweet-btn" %>
<% end %>
_tweet.html.erb
<li id="tweet-<%= tweet.id %>">
....
</li>
tweets_controller.rb
def create
@cat = Cat.find_by(id: params[:cat_id])
if logged_in? && current_user == @cat.user
@tweet = @cat.tweets.build(tweet_params)
respond_to do |format|
if @tweet.save
format.js
format.html { redirect_to @cat }
else
format.html { redirect_to @cat }
end
end
else
flash[:danger] = "It looks like you're trying to hack us! Go back and try again, but as a gentleman this time."
redirect_to current_user
end
end
create.js.erb
$( "ol#tweets" ).append( "tweet-<%= @tweet.id %>" )
谢谢!
答案 0 :(得分:1)
您的js.erb模板不会将推文部分呈现。尝试类似:
$( "ol#tweets" ).append( "<%= j render 'tweet', tweet: @tweet %>" )