简体   繁体   English

Rails:在其他模型上显示用户的Micropost

[英]Rails: Making User's Micropost show on another model

I have a User model that can post microblogs and it shows up on the user show page but I was wondering how would I be able to show the user made microblogs onto a model that the user belongs to for instance in this case a school. 我有一个可以发布微博的User模型,它显示在用户显示页面上,但我想知道如何将用户制作的微博显示到该用户所属的模型上,例如在这种情况下是一所学校。 Users belong to specific schools and the schools have many users under them. 用户属于特定学校,并且这些学校在其下拥有许多用户。 All help much appreciated! 所有帮助非常感谢!

User Show Page 用户显示页面

<div id="MicropostBody">
 <div>
 <% if @user.microposts.any? %>
    <table class="microposts">
      <%= render @microposts %>
    </table>
    <%= will_paginate @microposts %>
 <% end %>
 </div>
</div>

School Show Page Same thing? 学校秀页面同样的东西吗?

<div id="MicropostBody">
 <div>
 <% if @user.microposts.any? %>
    <table class="microposts">
      <%= render @microposts %>
    </table>
    <%= will_paginate @microposts %>
 <% end %>
 </div>
</div>

User Controller 用户控制器

def show
  @user = User.find(params[:id])
  @school = School.find(params[:id])
  @micropost = Micropost.new
  @microposts = @user.microposts.paginate(page: params[:page])
end

School Controller Same thing?? 学校负责人一样吗?

def show
  @user = User.find(params[:id])
  @school = School.find(params[:id])
  @micropost = Micropost.new
  @microposts = @user.microposts.paginate(page: params[:page])
end

New School Controller 新任校长

def show
  @school = School.find(params[:id])
  @user = User.new
  @micropost = Micropost.new
  @microposts = @school.microposts.paginate(page: params[:page])
  @micropost = current_school.microposts.build
end

Take a look back at the partials section of the Rails tutorial book before reading any further, if you're still struggling. 如果您仍在挣扎中,请在阅读任何其他内容之前先回顾一下Rails教程的“ partials”部分。

users/_microposts.html.erb

<div id="MicropostBody">
  <div>
    <% if microposts.any? %>
      <table class="microposts">
        <%= render microposts %>
      </table>
      <%= will_paginate microposts %>
    <% end %>
  </div>
</div>

Then in both views you can use: 然后在两个视图中都可以使用:

<%= render 'users/microposts', :microposts => @microposts %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM