Ruby on rails 3个关联模型的表格
我还是个新手,所以请原谅这个愚蠢的问题。我有三种型号:Ruby on rails 3个关联模型的表格,ruby-on-rails,ruby-on-rails-4,devise,Ruby On Rails,Ruby On Rails 4,Devise,我还是个新手,所以请原谅这个愚蠢的问题。我有三种型号: -用户(由Desive生成)、评论和发布 用户有许多帖子和评论 评论同时属于帖子和用户 帖子有很多评论,属于用户 My routes.rb resources :users do resources :posts do resources :comments end end 我的表格代码: <%= form_for([@user,@post,@comment]) do |f| %> ... <%
-用户(由Desive生成)、评论和发布
- 用户有许多帖子和评论
- 评论同时属于帖子和用户
- 帖子有很多评论,属于用户
resources :users do
resources :posts do
resources :comments
end
end
我的表格代码:
<%= form_for([@user,@post,@comment]) do |f| %>
...
<% end %>
...
我想生成到
user\u post\u comments\u path
,但上面的表单用于生成到post\u comments\u path
。为什么?我误解了什么吗。非常感谢Rails路由和表单处理非常混乱,我仍然一直在出错
我认为您的问题在于一些变量没有设置(nil
),因此rails无法确定您实际上在做什么
我还想建议你不要像那样嵌套你的路由,除非你为了URL而不得不这样做
在创建模型时,嵌套一层并使用当前用户
分配给模型就足够了。这也降低了发布其他用户ID时涉及的安全风险:
def create
@post = current_user.posts.build(post_params)
[...]
end
def create
@comment = current_user.comments.build(comment_params)
@comment.post = Post.find params[:post_id]
[...]
end
为了创建当前用户的帖子,我使用了与您之前推荐的相同的方法。但这里的问题是,我想在帖子中创建用户的评论。这里我们有3个模型关系。现在我使用这个技巧$comment=comment.new(comment\u params)$comment.user\u id=params[:user\u id]$comment.post\u id=params[:post\u id],它与关系无关。它只是手动设置属性。有什么建议吗?