RoR:我怎样才能让我的所有用户微博在一个地方出现?

时间:2012-09-21 19:25:18

标签: ruby ruby-on-rails-3

我希望它们显示在主页上。我想我可能遇到麻烦,因为有一个belongs_to has_many关系。每个微博属于用户,每个用户都有很多微博。我让它们显示在用户页面上(但这只是用户微博的列表,而不是每个人都是我想要的主页)。如果从视图中不清楚。我想要两个单独的列表。一个包含所有类型“购买”的所有微博的列表和所有“销售”微博的另一个列表。 Kind是微博数据库中的一列。现在没有任何显示,也没有错误...

这是app / views / static_pages / home.html.erb

<div id="purchases list">
  <ol class="microposts">
    <%= render @purchases unless @purchases.nil? %>
  </ol>
</div>

<div id="sales list">
  <ol class="microposts">
    <%= render @sales unless @sales.nil? %>
  </ol>
</div>

这是app / views / microposts / _micropost.html.erb(我不确定这是否重要)

<li>
  <span class="content"><%= micropost.content %></span>
  <span class="timestamp">
    Posted <%= time_ago_in_words(micropost.created_at) %> ago.
  </span>
  <% if current_user?(micropost.user) %>
    <%= link_to "delete", micropost, method:  :delete,
                                     confirm: "You sure?",
                                     title:   micropost.content %>
  <% end %>
</li>

在模型文件(micropost.rb)中对微博的定义中使用范围可能很重要

scope :purchases, where(:kind => "purchase")
  scope :sales, where(:kind => "sale")

这是microposts_controller.rb

class MicropostsController < ApplicationController
  before_filter :signed_in_user
  before_filter :correct_user,   only: :destroy


  def home
    @microposts=Micropost.all
    @purchases=@microposts.collect{ |m| m if m.kind == "purchase"}.compact
    @sales=@microposts.collect{ |m| m if m.kind == "sale"}.compact
  def show

    @micropost = Micropost.find(params[:id])
    @microposts = @user.microposts
    @purchases= @microposts.purchases
    @sales = @microposts.sales

  end

,这是users_controller.rb

class UsersController < ApplicationController
  before_filter :signed_in_user, 
                only: [:index, :edit, :update, :destroy, :following, :followers]
  before_filter :correct_user,   only: [:edit, :update]
  before_filter :admin_user,     only: :destroy

  def index
    @users = User.paginate(page: params[:page])
  end

  def show
    @user = User.find(params[:id])
    @micropost=Micropost.new
    @microposts = @user.microposts
    @purchases= @microposts.purchases
    @sales = @microposts.sales
  end

  def home

    @microposts = Micropost.all
    @purchases = @microposts.collect{ |m| m if m.kind == "purchase"}.compact
    @sales = @microposts.collect{ |m| m if m.kind == "sale"}.compact
  end

1 个答案:

答案 0 :(得分:1)

您的XController会在app/views/X中查找视图模板,因此您需要将home.html.erb移出app/views/static_pages并转移到app/views/usersapp/views/microposts。另外,为什么两个控制器中都有相同的home方法?

如果这对您不起作用,我想知道(a)您要浏览的网址,以及(b)routes.rb文件中的内容。