显示属于用户的不同对象

时间:2015-02-23 01:37:17

标签: ruby-on-rails ruby

所以,这很简单(我想),但我仍然很难绕过这个。我有一个应用,其中登录的User可以创建嵌套在Topics中的BookmarkstopicsUser还可以Like bookmark另一个用户创建。

在我的users/show.html.erb上,我正在尝试列出bookmarkslikes user已创建的所有内容。两者都有user_id,我认为这就是我可以称之为的方式,我只是迟钝而需要一些帮助。

我会在user_controlleruser/show.html.erb个文件中添加什么内容?

感谢您的帮助!

这是我的User.rb

    class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable,   :confirmable

has_many :topics
has_many :bookmarks, dependent: :destroy
has_many :likes, dependent: :destroy

#liked method takes a bookmark object and returns a like object if one    exists
def liked(bookmark)
likes.where(bookmark_id: bookmark.id).first
  end
end 

Like.rb

    class Like < ActiveRecord::Base

    #considered a simple join table, that represents a relation between        two objects (user/bookmark)
    belongs_to :user
    belongs_to :bookmark
    end

Bookmark.rb

 class Bookmark < ActiveRecord::Base

belongs_to :topic
belongs_to :user
has_many :likes, dependent: :destroy
end

1 个答案:

答案 0 :(得分:1)

在你的user_controller中:

def show
  @user = User.find(user_params[:id])
end


def user_params
 params.require(:user).permit(:id)
end

在show.html.erb中:

<% @user.bookmarks.each do |bookmark| %>
  <%= bookmark.name %>  #guessing here as I don't know your DB schema
<% end %>

<% @user.likes.each do |like| %>
  <%= like.name %>   #still guessing
<% end %>   

您说书签嵌套在主题中,但您没有在代码中显示。而不是用户模型:

has_many :bookmarks, dependent: :destroy

应该是

has_many :bookmarks, through: :topics, dependent: :destroy

您仍然可以通过相同的方式访问书签:

@user.bookmarks