在rails中显示某些用户的博文 [英] Show certain user's blog posts in rails

查看:107
本文介绍了在rails中显示某些用户的博文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,开始学习rails,当然也可以用个人博客(livejournal)来编写一个服务。我有脚本和用户模型(感谢Devise)。现在我试图显示某些用户在URL中的用户名/帖子的所有帖子,但是真的不明白如何使这种方式。
已经在路由中嵌套资源

 资源:用户做
资源:帖子
结束

  has_many:posts 

  belongs_to:user 

我为用户创建控制器吗?有没有正确的方法?



感谢你的回答。尝试学习轨道,但几乎每个教程,我发现结束脚手架,这不是很有帮助。



编辑1:感谢匹配的想法,我解决了一半的问题。另一个(未解决的)一半是选择某些用户写的帖子



编辑2:添加

  @user = User.where(:username => params [:username])
@posts = @ user.posts

对于控制器,但我在帖子控制器中有undefined方法`posts'错误。

解决方案

当您使用其中时,您将从查询中获取一组对象,而不是单个对象。

由于此您的 @user 变量中没有帖子方法。

也许你应该更改为这样的东西,只能检索一个用户

  @ user = User.find_by_username(params [:username])

这样你只有一个用户查询,您可以使用 .posts relashionship无错误。


Well, started to learn rails and of course started by writing a service with personal blogs (something like livejournal). I have posts scaffold and user model (thanks to Devise). Now I'm trying to show all posts by certain user with something like /username/posts in url but really can't understand how to make this rails-way. Already made nested resources in routes

resources :users do 
  resources :posts 
end

and connected user and post models with

has_many :posts

and

belongs_to :user

Should I create controller for user or not? Is there any proper way for this?

P.S. Thanks for the answer. Trying to study rails but almost every tutorial I found ends with scaffolding and that's not very helpful.

Edit 1: Thanks to the "match" idea I solved half of the problem. The other (unsolved) half is selecting posts written by certain user

Edit 2: Added

@user = User.where(:username => params[:username])
@posts = @user.posts

To controller, but I have "undefined method `posts'" error in posts controller.

解决方案

When you use where you get an array of objects from the query, not a single object.
And because of this you don't have the posts method on your @user variable.
Maybe you should change to something like this, to retrieve only one user:

@user = User.find_by_username(params[:username])

This way you have only one user queried and you can use the .posts relashionship without errors.

这篇关于在rails中显示某些用户的博文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆