我在我的 Rails 应用程序中有 BlogPosts 和 BlogCategories,还有一个 BlogPostCategorization 表将它们连接在一起。所以
class BlogCategory < ActiveRecord::Base
attr_accessible :name, :created_at, :updated_at, :blog_post_id
validates :name, presence: true, uniqueness: true
has_many :blog_post_categorizations
has_many :blog_posts, :through => :blog_post_categorizations
accepts_nested_attributes_for :blog_posts, allow_destroy: true
end
class BlogPost < ActiveRecord::Base
attr_accessible :body, :created_at, :updated_at, :image_url, :title
validates :body, :image_url, :title, presence: true
validates :title, uniqueness: true
has_many :blog_post_categorizations
has_many :blog_categories, :through => :blog_post_categorizations
accepts_nested_attributes_for :blog_categories, allow_destroy: true
end
class BlogPostCategorization < ActiveRecord::Base
belongs_to :blog_post
belongs_to :blog_category
end
现在,通过 ActiveAdmin,我希望能够创建新的博客文章,并为此博客文章创建类别。我有
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs "Blog Post" do
f.input :title
f.input :body, as: :html_editor
f.input :image_url
end
f.inputs "Blog Categories" do
f.has_many :blog_post_categorizations do |s|
s.input :blog_category
end
end
f.actions
end
但是,当我尝试访问新博客文章的事件管理页面时,我收到一条 Rails 错误消息,内容为“未定义的方法‘new_record?’”对于 nil:NilClass"在行中
f.has_many :blog_post_categorizations |s|
我做错了什么/遗漏了什么?
此外,下面包含在 POST 请求的参数散列中发送的 blog_category 数据
"blog_categories_attributes"=>{"1408936652467"=>{"name"=>"cooking"}, "1408936656066"=>{"name"=>"eat"}}
最佳答案
我认为这部分:
f.inputs "Blog Categories" do
f.has_many :blog_post_categorizations do |s|
s.input :blog_category
end
end
应该是:
f.inputs "Blog Categories" do
f.has_many :blog_categorys do |s|
s.input :name
end
end
编辑
考虑到您关于此问题的另一个问题,我会推荐一个(我希望)好的解决方法。自 strong_parameters默认情况下在 Rails 4 及更高版本中使用,而您使用的是 Rails 3.2.17,让我们让您的应用程序使用它。 所以有以下步骤:
安装
gem 'strong_parameters'
;在
config/application.rb
中设置为 falseconfig.active_record.whitelist_attributes
;在
;BlogPost
和BlogCategory
模型中包含 ActiveModel::ForbiddenAttributesProtection- 摆脱所有
attr_accessible
调用。
完成所有这些后,您可以将私有(private)方法中的所有参数列入白名单,如下所示:
private
def blog_post_params
params.require(:blog_post).permit(#all the params here)
end
并在#create 操作中使用 BlogPost.new(blog_post_params)
(在其他模型中相同,您可以在其中使用包含的模块)。现在您可以受益于 strong_parameters。
在 ActiveAdmin BlogPost
模型中,将所有允许的参数列入白名单:
permit_params :body, :created_at, :updated_at, :image_url, :title, blog_categories_attributes: [:id, :name, :_destroy, :blog_post_id]
在 Controller 中
controller do
def permitted_params
params.permit blog_posts: [:body, :created_at, :updated_at, :image_url, :title, blog_categories_attributes: [:id, :name, :_destroy, :blog_post_id]]
end
end
更准确地查看文档中的 strong_params 用法。还要仔细检查拼写错误/错误的命名/下划线(因为我推测了一些事情)。
祝你好运!
关于ruby-on-rails - 通过连接表无法工作的多对多关系的 Rails ActiveAdmin 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25438318/