Ruby on Rails的交往形式 [英] Ruby on Rails Association Form

查看:121
本文介绍了Ruby on Rails的交往形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用ROR提出一个web应用程序,我想不通这种形式正确的语法是什么。我目前正在code的评论和帖子的关联类型。

 <%=的form_for @comment做| F | %GT;
 &所述p为H.;
 <%= f.hidden_​​field:USER_ID,:价值=> current_user.id%GT;
 <%= f.label:发表评论%GT;< BR />
 <%= f.text_area:评论%GT;
 &所述; / P> &所述p为H.;
 <%= f.submit添加注释%GT;
 &所述; / P>
<%结束%GT;


解决方案

您的形式是很好,除了第一行(你不需要隐藏字段为USER_ID,这就是通过你的关系做了):

 <%=的form_for(@comment)做| F | %GT;

应该是:

 <%=的form_for([@后,@comment])做| F | %GT;

现在您呈现一个表单创建或更新一个特定的信息进行评论。

不过,你应该改变你的模型和控制器。

 类帖子
  的has_many:评论
结束类评论
  belongs_to的:岗位
结束

这将让您使用@ post.comments,呈现出属于特定职位的所有意见。

在你的控制器,你可以访问的评论针对特定发布:

 类CommentsController< ApplicationController中
  高清指数
    @post = Post.find(PARAMS [:POST_ID])
    @comment = @ p​​ost.comments.all
  结束
结束

这样,您就可以访问注释索引担任某一职位。

更新

还有一件事,你的路由也应该是这样的:

  AppName的:: Application.routes.draw做
   资源:帖子做
     资源:评论
   结束
结束

这会给你访问post_comments_path(以及更多的路线)

So i'm making a web app using ROR and I can't figure out what the right syntax for this form is. I'm currently making an association type of code for comments and posts.

<%= form_for @comment do |f| %>
 <p>
 <%= f.hidden_field :user_id, :value => current_user.id %>
 <%= f.label :comment %><br />
 <%= f.text_area :comment %>
 </p>

 <p>
 <%= f.submit "Add Comment" %>
 </p>
<% end %>

解决方案

Your form is fine, except the first line (and you don't need a hidden field for the user_id, thats done through your relationship):

<%= form_for(@comment) do |f| %>

Should be:

<%= form_for([@post, @comment]) do |f| %>

Now you render a form for creating or updating a comment for a particular post.

However, you should change your model and controller.

class Post
  has_many :comments
end

class Comment
  belongs_to :post
end

This will give you access to @post.comments, showing all comments belonging to a particular post.

In your controller you can access comments for a specific post:

class CommentsController < ApplicationController
  def index
    @post = Post.find(params[:post_id])
    @comment = @post.comments.all
  end
end

This way you can access the index of comments for a particular post.

Update

One more thing, your routes should also look like this:

AppName::Application.routes.draw do
   resources :posts do
     resources :comments
   end
end

This will give you access to post_comments_path (and many more routes)

这篇关于Ruby on Rails的交往形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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