1
所以我试图让我的主题控制器创建一个新的主题与初始职位。我的新主题视图看起来像这样post_attributes的未经允许的参数
<% @title = "New Topic" %>
<h1>New Topic</h1>
<%= form_for [@topic.forum, @topic] do |f| %>
<%= render "topic_form", f: f %>
<%= f.submit "Create Topic", class: "btn btn-primary" %>
<% end %>
下面是部分以及
<% if @topic.errors.any? %>
<div class="alert alert-danger">
<p>The form contains <%= pluralize(@topic.errors.count, "error") %>.</p>
</div>
<ul>
<% @topic.errors.full_messages.each do |message| %>
<li class="text-danger"> <%= message %> </li>
<% end %>
</ul>
<% end %>
<div class='form-group'>
<%= f.label :title, "Title*" %>
<%= f.text_field :title, class: 'form-control' %>
</div>
<%= f.fields_for :posts do |post| %>
<div class='form-group'>
<%= post.label :content, "Content*" %>
<%= post.text_area :content, size: "50x6", class: 'form-control' %>
</div>
<% end %>
主题模型的
class Topic < ActiveRecord::Base
belongs_to :forum
belongs_to :user
has_many :posts, :dependent => :destroy
validates :title, presence: true
accepts_nested_attributes_for :posts, allow_destroy: true
end
主题控制器
def new
forum = Forum.find(params[:forum_id])
@topic = forum.topics.build
post = @topic.posts.build
end
def create
forum = Forum.find(params[:forum_id])
@topic = forum.topics.build(topic_params)
@topic.last_poster_id = current_user.id
@topic.last_post_at = Time.now
@topic.user_id = current_user.id
if @topic.save then
flash[:success] = "Topic Created!"
redirect_to @topic
else
render 'new'
end
end
凭借雄厚的参数的事情
def topic_params
params.require(:topic).permit(:title, :post_attributes => [:id, :topic_id, :content])
end
但无论我做什么它打破。开发日志说有
Unpermitted parameters: posts_attributes
我已经在网上搜索了无数个小时,并没有获胜。任何人有任何想法如何解决这个问题。现在,当我点击主题新视图中的提交按钮时,它会提交标题,但是您放入的内容会丢失,当我创建新帖子时,它工作得很好,并打印出用户放入的内容。在创建新主题时中断,唯一中断的部分是内容部分。
我认为这实际上解决了问题,但快速提出问题,因为我的视图需要user_id来访问用户名。当我执行'params.require(:topic).permit(:title,:post_attributes => [:id,:user_id => current_user.id,:topic_id,:content])''这不起作用? – G3tinmybelly
我需要以某种方式将user_id链接到最初的帖子。有任何想法吗? – G3tinmybelly
我想我想通了。在创建方法中,我刚刚做了一个janky设置,其中@ topic.posts [length] .user_id = current_user.id。如果您对如何解决这个问题有更好的想法,请成为我的客人。 – G3tinmybelly