Rails 4:如何在索引页面上获取ID?

时间:2014-03-23 09:09:14

标签: ruby-on-rails-4 has-many

我有Model1,它与Model2有“has_many”rel。我需要的是在Model1索引页面上的每个对象下为Model2创建表单。让我们说我有推文,每条推文都有表格来添加评论。我在理解如何操作,如何在索引页面上获取Tweet id等方面遇到麻烦。

2 个答案:

答案 0 :(得分:0)

让我们说推文有很多评论,所以创建模型推文和评论关系也会创建控制器推文和评论。

在你的推文/索引页面中有推文列表,右边和脚本就是这样。

<% @tweets.each do |tweet| %>
 <%= link_to "show tweet", tweet_path(tweet) %>
<% end %>

显示推文链接将带您显示页面,您将从params获得推文ID。现在您可以在此展示页面中填写评论表格,如下所示

<%= form_for @comment do |f|%>
 <%= f.text_area :comment %>
 <%= f.submit %>
<% end %>

路由文件:

resources :tweets do
 resources :comments
end

我刚刚通过提供rails-views的示例为您提供了一些工作方式,因此请正确检查控制器中的操作。

答案 1 :(得分:0)

似乎所有你需要做的就是让@comment表单在索引页面上的每个@tweet下工作:

- @tweets.each do |tweet|
  = tweet.name `#to show tweet`
  - tweet.comments.each do |comment| `#to show each tweet comment`
    = comment.content 
    = form_for [tweet, Comment.new] do |f| `#form forcomment belonging to this particular tweet`
     = f.text_field :content
     = f.submit

希望有所帮助:)