我收到以下错误
PostsController中的UnknownAttributeError #new
未知属性:company_id
发布控制器
def new
@company = Company.find(params[:company_id])
@post = @company.posts.build
end
def create
@company = Company.find(params[:company_id])
@post = @company.posts.build(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:title, :summary, :body)
end
路线
resources :companies do
resources :posts
end
模型
class Post < ActiveRecord::Base
belongs_to :company
end
class Company < ActiveRecord::Base
belongs_to :user, dependent: :destroy
has_many :posts
end
形式
<%= form_for (@post) do |f| %>
<div class="form-group">
<%= f.label :Post_Title %>
<%= f.text_field :title, class: "form-control", placeholder: "Post Title" %>
</div>
<div class="form-group">
<%= f.label :Post_Summary %>
<%= f.text_area :summary, class: "form-control", placeholder: "Post Summary" %>
</div>
<div class="form-group">
<%= f.label :Post_Post %>
<%= f.text_area :body, class: "form-control", placeholder: "The Post" %>
</div>
<div class="form-group">
<%= f.submit :Submit, class: "btn btn-success" %>
</div>
<% end %>
我希望每个帖子都属于公司,帖子的表格中包含属性company_id
。我无法弄清楚为什么这不起作用。
答案 0 :(得分:0)
在company_id
中添加post_params
,
<强> posts_controller.rb 强>
private
def post_params
params.require(:post).permit(:title, :summary, :body, :company_id)
end
在表单中添加company_id
<%= form_for (@post) do |f| %>
<div class="form-group">
<%= f.label :Post_Title %>
<%= f.text_field :title, class: "form-control", placeholder: "Post Title" %>
</div>
<div class="form-group">
<%= f.label :Post_Summary %>
<%= f.text_area :summary, class: "form-control", placeholder: "Post Summary" %>
</div>
<div class="form-group">
<%= f.label :Post_Post %>
<%= f.text_area :body, class: "form-control", placeholder: "The Post" %>
</div>
<%= hidden_field_tag 'company_id', @company.id %>
<div class="form-group">
<%= f.submit :Submit, class: "btn btn-success" %>
</div>
<% end %>
答案 1 :(得分:0)
当您嵌套资源时,您将最终破坏路线中的许多默认路径。通常,这只是将posts_path
更新为company_posts_path(@company)
的简单修复方法。
如果是此表单,则form_for
会将您发送到旧的posts#new
,而不是新嵌套的resources :posts
。我会继续猜测你在你发布的嵌套资源之外的路线中仍然有form_for(@post)
。
要解决此问题,您需要将form_for([@company, @post])
的路径更改为@post
。这样,表单就会知道会将您发送到@company
内嵌套的{{1}}表单。