Rails 5:对象的父 ID 在新操作和创建操作之间丢失

Rails 5: Object's parent ID being lost between the new action and the create action

我正在尝试创建一个 post,它将包含表单所在的 forum_id。我需要将两个 ID 都保存在对象中才能实现。

我在 new 操作中使用 @post = Forum.find(params[:forum_id]).posts.build 初始化了一个新的 @post 这将吐出包含 forum_id 的 post 的未保存实例,正如预期的那样。

然后我在这里填写我的表格:

<%= form_for @post, :url => {:controller => "posts", :action => "create"} do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %>
    <%= f.text_field :title, class: "form-control" %>
  </div>

  <div class="field">
    <%= f.label :description %>
    <%= f.text_area :description, class: "form-control" %>
  </div>

  <div class="actions">
    <%= f.submit class: "btn btn-primary" %>
  </div>
<% end %>

当我单击提交按钮并在 create 操作中的 @post = Post.new(post_params) 行后使用 byebug 检查 post_params 时,只有 :title 和 [=24= 】 过来。 forum_id 在操作之间丢失,没有它我无法保存 @post。我已将 :forum_id 列入我的 post_params 白名单,但它没有通过。我认为如果 post 的实例是在带有 forum_idnew 动作中创建的,那么它应该持续到 post_params 中的 create 动作中,但是有些东西这里是错误的。以下是可能有助于解决我的问题的相关信息。

我的模型的关系:

# User model
has_many :forums
has_many :posts

# Forum model
belongs_to :user
has_many :posts

# Post model
belongs_to :user
belongs_to :forum

# post_controller
def new
  @post = Forum.find(params[:forum_id]).posts.build
end

Post 控制器

def create
  @post = Post.new(post_params)
  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 }
    else
      format.html { render :new }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end

...
 # Rest of actions
...
def post_params
    params.require(:post).permit(:title, :description, :forum_id, :user_id)
  end
end

表单没有提交 forum_id 因为那里不存在

我认为您需要将其添加到该表格中

<%= f.hidden_field :forum_id %>