【发布时间】:2015-10-17 04:04:50
【问题描述】:
后模型
has_many :post_contents
accepts_nested_attributes_for :post_contents
PostContents 模型
belongs_to :post
发布_form.html.erb
<%= form_for(@post) do |f| %>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>
</div>
<div class="form-group">
<%= f.label "Description" %>
<%= f.text_field :body, class: 'form-control', placeholder: "Enter post description" %>
</div>
<div class="form-group">
<%= fields_for :post_content do |x| %>
<%= x.label :body %>
<%= x.cktext_area :body, :ckeditor => {:toolbar => 'Full'} %>
<% end %>
</div>
<div class="form-group">
<%= f.submit "Save", class: 'btn btn-success' %>
</div>
<% end %>
</div>
</div>
我试过 post_content 和 post_contents
PostContents 引用帖子
class CreatePostContents < ActiveRecord::Migration
def change
create_table :post_contents do |t|
t.references :post, index: true, foreign_key: true
t.text :body
t.timestamps null: false
end
end
end
和 AddCurrentPostContentIdToPosts
class AddCurrentPostContentIdToPosts < ActiveRecord::Migration
def change
add_column :posts, :current_post_content_id, :integer
add_index :posts, :current_post_content_id
end
end
发布内容控制器
def new
@post_content = PostContent.new
end
def create
@post_content = PostContent.new(post_content_params)
respond_to do |format|
if @post_content.save
format.html { redirect_to @post_content, notice: 'Post content was successfully created.' }
format.json { render :show, status: :created, location: @post_content }
else
format.html { render :new }
format.json { render json: @post_content.errors, status: :unprocessable_entity }
end
end
def post_content_params
params.require(:post_content).permit(:post_id, :body, :posts)
end
end
后控制器
def new
@post = Post.new
authorize @post
end
def create
@post = Post.new(post_params)
@post.user = current_user
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
def post_params
params.require(:post).permit(:title, :body, :current_post_content_id, post_contents_attributes: [:body])
end
end
抱歉,重复的字段 (:body)。
在创建新帖子时,您有什么建议将 PostContent :body 字段添加到“posts/_form”中?
【问题讨论】:
-
您的问题到底是什么?你遇到错误还是什么?
-
没有收到错误。我什么也得不到。我正在尝试创建一个新帖子(:title 和:body),并通过一个简单的步骤将 post_content(:body)附加到新帖子。目前,我必须创建一个带有标题和正文的新帖子,然后我必须创建一个新的 post_content 并将 post_id 附加到 post_content 中的 :body 字段
-
您使用的是什么版本的导轨?你检查过强参数吗?这可能会阻止包含关联信息的参数。提交表单时能否提供请求参数?
-
我正在使用 rails 4。这是我正在使用的表单的参数。 params.require(:post).permit(:title, :body, :current_post_content_id)
-
抱歉,我的意思是您在提交表单后在控制器中获得的实际参数哈希。另外,你能试试这个:params.require(:post).permit(:title, :body, post_content_attributes: [:body]) 见:edgeapi.rubyonrails.org/classes/ActionController/…
标签: ruby-on-rails rails-models fields-for