【问题标题】:How to create has_many associated fields with the parent field in rails 4如何在rails 4中创建has_many关联字段与父字段
【发布时间】:2014-08-25 00:02:52
【问题描述】:

我正在寻找一种与评论一起创建评论的方法。

下面是带有架构的架构表 1.帖子表

# 表名:posts # # id :integer not null, 主键 # 发布:字符串(255) # post_content :string(255) # created_at : 日期时间 # 更新时间:日期时间 #

class Post < ActiveRecord::Base
    has_many :comments
    accepts_nested_attributes_for :comments
end

2.评论表

# 表名:cmets # # id :integer not null, 主键 # 评论:字符串(255) # post_id :整数 # created_at : 日期时间 # 更新时间:日期时间 # # 索引 # # index_cmets_on_post_id (post_id) #

class Comment < ActiveRecord::Base
  belongs_to :post
end

现在,我想创建带有评论的帖子。我如何实现它?请帮忙。

表格部分

<%= form_for(@post) do |f| %>
  <%= f.text_field :post %>
  <%= f.text_field :post_content %>
  <br>
  <span>put comments</span>  
  <%= f.fields_for :comments do |s|%>
    <%= s.text_field :comment %>
    <%= s.hidden_field :post_id ,value: @post.id%>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

控制器代码

class PostsController < ApplicationController

  def new
    @post = Post.new
    @post.comments.build
  end

  def create
    @post = Post.new(post_params)
    @post.comments.build
    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      end
    end
  end

  private

    def post_params
      params.require(:post).permit(:post,:post_content,comment_attributes:[:comment])
    end
end

【问题讨论】:

  • 第一步:在你的PostsControllernew方法中添加这个@post = Post.new@post.comments.build
  • @Pavan,你能给我一些关于这个的教程或文件吗?
  • 作为,我正在使用我正在使用与您所说的相同。但它使用 nil 来创建评论
  • 您的post_params 应该是params.require(:post).permit(:post,:post_content,comments_attributes:[:comment]) 它是comments_attributes 而不是comment_attributes
  • 我会添加它作为答案。

标签: ruby-on-rails


【解决方案1】:

由于您在 Post 模型中有 has_many :comments,您的 post_params 方法应该是

def post_params
  params.require(:post).permit(:post,:post_content,comments_attributes:[:comment])
end

注意变化,即 comments_attributes 而不是 comment_attributes

【讨论】:

    猜你喜欢
    • 2017-11-27
    • 2015-08-17
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    相关资源
    最近更新 更多