我正在使用 Rails 建立一个论坛。
当您创建一个主题时,它将具有来自主题类的名称和描述,以及来自帖子类的帖子内容......(当您创建一个主题时,您会自动创建一个包含该内容的帖子)
含义:对于每个主题,您可以有多个帖子对于每个帖子,您必须有一个主题。
出于某种原因,当我创建一个主题时,它会保存该主题的输入,但会丢弃 Post 类的输入。
我环顾 Stackoverflow 并注意到一些类似的问题,并尝试了许多答案只是为了得到错误或没有任何变化。( accepts_nested_attributes_for 不将子属性保存到数据库中,
楷模
class Topic < ActiveRecord::Base
belongs_to :forum
has_many :posts, :dependent => :destroy
belongs_to :user
accepts_nested_attributes_for :posts
end
class Post < ActiveRecord::Base
belongs_to :topic
end
控制器 - 主题
class TopicsController < ApplicationController
before_action :set_topic, only: [:show, :edit, :update, :destroy]
def index
@topics = Topic.all
end
def new
@topic = Topic.new
responses = @topic.posts.build
end
def create
@topic = Topic.new(topic_params)
if @topic.save
flash[:success] = "Topic Posted"
redirect_to "/forums/#{@topic.forum_id}"
else
render :new
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_topic
@topic = Topic.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def topic_params
params.require(:topic).permit(:name, :description, :last_poster_id, :last_post_at, :forum_id,
posts_attributes: [:id, :content] )
end
end
_形式
<%= form_for(@topic) do |f| %>
<% if params[:forum] %>
<input type="hidden"
id="topic_forum_id"
name="topic[forum_id]"
value="<%= params[:forum] %>" />
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<%= f.fields_for :responses do |p| %>
<%= p.label :content %><br />
<%= p.text_area :content %>
<% end %>
<%= f.submit :class => "btn btn-primary" %>
<% end %>