我读了这篇文章,它对第一步很有帮助,现在我在第二步。我需要控制器和表单方面的帮助。
假设这是我的模型:
User
has_many :posts
has_many :comments
Post
belongs_to :user
has_many :comments
Comment
belongs_to :user
belongs_to :post
这些是我的桌子:
User
id
Post
id
user_id
Comment
id
user_id
post_id
在最初的帖子中,用户 ID 会自动添加到内容中,方法是将其添加到控制器的创建部分:
@post = current_user.post.build(params[:post])
如果评论同时属于用户和帖子,我如何让它自动添加 post_id 以及 user_id?目前,我似乎只能通过这样做来插入 user_id:
current_user.comments.build(params[:comment])
我是新来的铁路。我认为最好的方法不是使该字段可访问并在表单中添加一个隐藏字段,难道没有另一种方法吗?
这些是我更新的路线:
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
sessions POST /sessions(.:format) sessions#create
new_session GET /sessions/new(.:format) sessions#new
session DELETE /sessions/:id(.:format) sessions#destroy
Post_comments GET /posts/:Post_id/comments(.:format) comments#index
POST /posts/:Post_id/comments(.:format) comments#create
new_Post_Comment GET /posts/:Post_id/comments/new(.:format) comments#new
edit_Post_Comment GET /posts/:Post_id/comments/:id/edit(.:format) comments#edit
Post_Comment GET /posts/:Post_id/comments/:id(.:format) comments#show
PUT /posts/:Post_id/comments/:id(.:format) comments#update
DELETE /posts/:Post_id/comments/:id(.:format) comments#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_Post GET /posts/new(.:format) posts#new
edit_Post GET /posts/:id/edit(.:format) posts#edit
Post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
root / static_pages#home
signup /signup(.:format) users#new
signin /signin(.:format) sessions#new
signout DELETE /signout(.:format) sessions#destroy
start /start(.:format) posts#new