我一整天都在搜索这个答案的stackoverflow。我有一个表单来创建一个新的话题。第一篇文章也应该与主题一起创建。一切都很好,除了user_id没有被保存到帖子。accepted_nested_attributes_for with hidden_field
邮政模型
class Post < ActiveRecord::Base
belongs_to :topic
belongs_to :user
end
主题模型的
class Topic < ActiveRecord::Base
belongs_to :forum
belongs_to :user
has_many :posts
accepts_nested_attributes_for :posts
end
柱控制器
class PostsController < ApplicationController
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to topic_path(@post.topic_id)
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:content, :topic_id, :topic_name, :user_id)
end
端
主题控制器
class TopicsController < ApplicationController
def new
@topic = Topic.new
@topic.posts.build
end
def create
@topic = Topic.new(topic_params)
if @topic.save
redirect_to @topic
else
render 'new'
end
end
private
def topic_params
params.require(:topic).permit(
:topic_name,
:forum_id,
:user_id,
posts_attributes: [:id, :content, :topic_id, :topic_name, :user_id ])
end
end
新/话题查看
<%= form_for(@topic) do |f| %>
<%= f.hidden_field :forum_id, :value => params[:forum_id] %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.label :topic_name %>
<%= f.text_field :topic_name %>
<%= f.fields_for :posts do |p| %>
<%= p.label :content %>
<%= p.text_area :content %>
<% end %>
<%= f.submit "Post Topic", class: "btn btn-large btn-success" %>
<% end %>
我不完全知道为什么USER_ID没有被传递到岗位。希望有人比我聪明可以帮助我学习怎样做:)
UPDATE
我改变了强劲PARAMS在我的主题控制器此。
def topic_params
params.require(:topic).permit(
:topic_name,
:forum_id,
posts_attributes: [:content, :topic_id, :id, '_destroy' ]).merge(:user_id => current_user.id, posts_attributes: [:user_id => current_user.id])
end
现在,user_id正在工作,但没有任何posts_attributes像:内容正在保存。我有很多的乐趣与此一..
我不知道,我不应该使用hidden_field。我使用了你的代码,并为#<用户:0x5ef0c80>获取错误未定义的方法'with_indifferent_access'。时间搜索一些更多。我想我现在走在正确的轨道上。 –
根据您最近的更新更新了我的答案。 –
这给我的错误没有隐式转换为整数字符串。回到搜索。 –