我以为我在一定程度上理解了 Rails 3 中的 Ajax,但我认为我在某个地方混淆了自己或误解了某些东西。我的理解是,如果我想在同一页面上调用不同的内容,那么我会为该特定操作创建一个 js.erb 文件。例如,如果我有一个 tynewyddnews 的操作,我将有一个 tynewyddnews 视图和一个 tynewyddnews.js.erb 文件。
然后,我创建一个要在该页面上呈现的部分,并在我的 .js.erb 文件中调用该部分。
例子
看法
<% @tynewyddpost.each do |t| %>
<li>
<% single = t.photos.first %>
<a class="photo" href="#"><%= image_tag(single.avatar.url(:thumbnail_news_images)) %></a>
<p><%= link_to t.title, tynewyddnews_path(:type => 'tynewyddnews'), :post_id => t.id, :remote => true %></p>
<p class="date"><%= date_output(t.published_on) %></p>
</li>
<% end %>
<div class="post-item">
<h2><%= @tynewyddpostlatest.title %></h2>
<div id="work-samples">
<% for photo in @tynewyddpostlatest.photos %>
<%= image_tag(photo.avatar.url(:news_images), :class => 'work-sample') %>
<% end %>
</div>
<p class="post-description"><%= @tynewyddpostlatest.comments.html_safe %></p><a class="post-more" href="#">Continue Reading »</a>
<div class="post-item-panel">
<ul>
<li class="date">
<p><%= date_output(@tynewyddpostlatest.published_on) %></p>
</li>
</ul>
</div>
</div>
所以历史帖子在左侧,最新帖子在中间
.js.erb
<% if params[:type] == 'tynewyddnews' %>
jQuery('.post-item').html('<%= escape_javascript(render partial: 'tynewyddnewspost') %>');
<% end %>
部分的
<div class="post-item">
<h2><%= @tynewyddpost.title %></h2>
<div id="work-samples">
<% for photo in @tynewyddpost.photos %>
<%= image_tag(photo.avatar.url(:news_images), :class => 'work-sample') %>
<% end %>
</div>
<p class="post-description"><%= @tynewyddpost.comments.html_safe %></p>
<div class="post-item-panel">
<ul>
<li class="date">
<p><%= date_output(@tynewyddpost.published_on) %></p>
</li>
</ul>
</div>
</div>
控制器
def tynewyddnews
tynewyddpost = Post.tynewydd_posts.find(params[:post_id])
tynewyddpost.shift
@tynewyddpost = tynewyddpost
@tynewyddpostlatest = Post.tynewydd_posts.first
end
tynewydd_posts 是一个范围
scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}, :order => "posts.published_on DESC"
所以我目前的问题是当我尝试渲染页面时出现错误
Couldn't find Post without an ID
为长篇道歉,但如果有人能指出我正确的方向,那就太好了
谢谢