Rails 3的link_to部分带有for循环

Rails 3 link_to partial with for loop inside

本文关键字:for 循环 to link Rails      更新时间:2023-09-26

我以前从未编程过,我很难让link_to在我的Rails 3应用程序内的用户配置文件中呈现相应的:partial

  1. _profile_credits (为了这个问题,我专注于_profile_credits)
  2. _profile_about
  3. _profile_reviews

我要做的是点击下面的:

<li><%= link_to "Credits", profile_credits_profile_path(:id => @profile.id), :remote => true %></li>

并有以下部分(_profile_credits)加载并呈现每个信用在@user.credits:

<% for credit in @user.credits %>
  <div class="credit">
  </div>
<% end %>

我试图渲染部分的地方是在链接下面和div容器里面。下面的HTML显示了div中链接的位置,以及我希望从partials中加载信息的位置:

<div id="tabs">
  <ul id="infoContainer">
    <li><%= link_to "Reviews", profile_reviews_profile_path(:id => @profile.id), :remote => true %></li>
    <li><%= link_to "About", profile_about_profile_path(:id => @profile.id), :remote => true %></li>
    <li><%= link_to "Credits", profile_credits_profile_path(:id => @profile.id), :remote => true %></li>
  </ul>
  <div id="tabs-1">
    ##load information from the partials inside `<div id="tabs-1">
  </div>
</div><!-- end tabs -->

和我剩下的代码…

我的profiles_controller#profile_credits动作:

def profile_credits
  respond_to do |format|
    format.js { render :layout => false }
  end
end

In my routes.rb:

resources :profiles do
  get :profile_credits, :on => :member
end

My profile_credits.js.erb:

$( "#tabs" ).html( "<%= escape_javascript( render (:partial => "profile_credits", :locals => { :id => @profile.id } ) ) %>" );

当我点击链接时,什么也没有发生。我试着遵循各种Rails 3 UJS示例,但不能得到它。有一次,我在ProfilesController profile_credits动作中指定了更多内容。然而,如果我在别人的个人资料上,我的信用就会加载,而不是我正在浏览的用户的信用。有人能帮我弄明白吗?

我终于让它工作了。给定一个<div>,其中包含一个<ul>导航和一个<div>的加载内容,下面是我的代码:

HTML for my container:

<div id="tabs">
  <ul id="infoContainer">
    <li><%= link_to "Reviews", profile_reviews_profile_path, :remote => true %></li>
    <li><%= link_to "About", profile_about_profile_path, :remote => true %></li>
    <li><%= link_to "Credits", profile_credits_profile_path, :remote => true %></li>
  </ul>
  <div id="tabs-1">
    <%= render :partial 'profile_reviews %> #default
  </div>
</div><!-- end tabs -->

_profile_credits.html.erb partial:

<% for credit in @user.credits %>
  <div class="credit">
  </div>
<% end %>

profile_credits.js.erb:

$( "#tabs-1" ).html( "<%= escape_javascript( render (:partial => "profile_credits" ) ) %>" );
profile_credits.rb控制器:
def profile_credits
  @profile = Profile.find(params[:id])
  @user = User.find(@profile.user_id)
  @credits = User.find(@profile.id).credits
  respond_to do |format|
    format.html { render :layout => nil }
    format.xml
    format.js { render :layout => nil }
  end
end