質問

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. 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.

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帰属
所属していません StackOverflow
scroll top