【问题标题】:ActiveAdmin won't save has many and belongs to many fieldActiveAdmin 不会保存很多并且属于很多领域
【发布时间】:2013-06-19 20:37:34
【问题描述】:

我有 2 个模型。类别和帖子。它们使用 has_many_and_belongs_to_many 关系连接。我检查了rails控制台并且关系有效。

我在 activeadmin 中创建了复选框以使用此表单字段设置帖子类别:

f.input :categories, as: :check_boxes, collection: Category.all

问题是当我尝试保存它时,因为所有其他字段数据(标题、正文、元信息等)都已保存,但即使我取消选中它或也选中了另一个,类别仍保持不变。

我正在使用这样的强参数:

post_params = params.require(:post).permit(:title,:body,:meta_keywords,:meta_description,:excerpt,:image,:categories)

请给我一些建议,让活跃的管理员也保存类别!

最好的祝愿, 马特

【问题讨论】:

    标签: activeadmin has-and-belongs-to-many


    【解决方案1】:

    在 AA 中试试这个:

        controller do
          def permitted_params
            params.permit post: [:title, :body, :meta_keywords, :meta_description, :excerpt, :image, category_ids: []]
          end
        end
    

    【讨论】:

      【解决方案2】:

      在 /app/admin/post.rb 中加入这样的内容:

      ActiveAdmin.register Post do
        permit_params :title, :body, :meta_keywords, :meta_description, :excerpt, :image, category_ids: [:id]
      end
      

      如果您使用的是accepts_nested_attributes_for,那么它看起来像这样:

      ActiveAdmin.register Post do
        permit_params :title, :body, :meta_keywords, :meta_description, :excerpt, :image, categories_attributes: [:id]
      end
      

      【讨论】:

        【解决方案3】:

        我已经测试过了,这可能对你和其他人也有效

        # This is to show you the form field section
        form do |f|
            f.inputs "Basic Information" do
                f.input :categories, :multiple => true, as: :check_boxes, :collection => Category.all
            end
            f.actions
        end
        
        # This is the place to write the controller and you don't need to add any path in routes.rb
        controller do
            def update
                post = Post.find(params[:id])
                post.categories.delete_all
                categories = params[:post][:category_ids]
                categories.shift
                categories.each do |category_id|
                    post.categories << Category.find(category_id.to_i)
                end
                redirect_to resource_path(post)
            end
        end
        

        如果您也使用强参数,请记住允许属性(请参阅上面的 zarazan 回答:D)

        引用自http://rails.hasbrains.org/questions/369

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-22
          • 1970-01-01
          相关资源
          最近更新 更多