在rails中显示某些用户的博文 [英] Show certain user's blog posts in rails
问题描述
已经在路由中嵌套资源
资源:用户做
资源:帖子
结束
与
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屋!