如何仅显示用户名为“abc”的内容?

时间:2013-11-28 22:55:17

标签: ruby-on-rails ruby authentication devise

我有一个东西模型:

class Thing < ActiveRecord::Base
  belongs_to :user

  has_attached_file :image, :styles => { :medium => '300x300>', :thumb => '100x100>' }

  validates :image, presence: true
  validates :description, presence: true
end

我还有一个用户模型:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :things

  validates :name, presence: true
  validates :username, presence: true
  validates :email, presence: true
end

我的UsersController看起来像这样:

class UsersController < ApplicationController
  def show
    @user = User.find_by_username(params[:username])
  end
end

当我导航到localhost:3000 / users / Delacram,其中Delacram是用户名时,如何仅显示具有Delacram用户名的Things?

2 个答案:

答案 0 :(得分:2)

鉴于你有@user有许多things

@user.things

你可以循环:

@user.things.each do |thing|
  = thing.description
  ...

答案 1 :(得分:1)

同样......在控制器中,您可以调用@things = @user.things的实例。然后在您的视图中,您可以致电= render @things。这将查看views/things/_thing.html.haml,并将该文件中的任何内容放到页面上,用于@thing的每个实例。

Rails魔术......

相关问题