【问题标题】:Assign categories to a newly created post with Ruby and Padrino使用 Ruby 和 Padrino 为新创建的帖子分配类别
【发布时间】:2016-07-15 13:15:45
【问题描述】:

我正在开发我的轻量级 Padrino CMS,它与 Wordpress 的功能非常相似。创建新帖子时,我希望能够将它们分配给许多现有类别。不知何故,我无法让我的表单工作。

我的模型是这样的:

后模型

 class Post < ActiveRecord::Base
   belongs_to :account
   has_many :categorizations
   has_many :categories, :through => :categorizations
   accepts_nested_attributes_for :categories
 end

类别模型

 class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :posts, :through => :categorizations
  belongs_to :category
 end

分类模型

 class Categorization < ActiveRecord::Base
  belongs_to :post
  belongs_to :category
 end

我还为联合表创建了迁移

 class CreateCategorizations < ActiveRecord::Migration
  def self.up
   create_table :categorizations do |t|
     t.integer :category_id
     t.integer :post_id
     t.timestamps
   end
  end

  def self.down
   drop_table :categorizations
  end
 end

这是表单的相关部分

  <% fields_for :categories do |c| %>
    <fieldset class='control-group <%= error ? 'has-error' : ''%>'>
      <%= c.label 'Category title', :class => 'control-label' %>
      <div class='controls'>
        <%= c.select(:id, :collection => @categories, :fields => [:title, :id], :include_blank => true, :multiple => true, :class => 'form-control input-xlarge input-with-feedback') %>
       <span class='help-inline'><%= error ? c.error_message_on(:id) : "Select a category if there is a parent category" %></span>
     </div>
   </fieldset>
  <% end %>

我不知道我错过了什么,但没有创建关联。在创建过程中我没有在控制器中提及类别,但我确实用现有的类别填充了下拉列表。不知何故,我想将它们与新帖子相关联。

如果有人能指出我正确的方向,我将不胜感激。我得到的错误是这样的:

/admin/posts/create 处的 NoMethodError nil:NilClass 的未定义方法“每个” 文件:collection_association.rb 位置:替换行:383

表单 POST 数据包含:

发布

变量authentity_token

值“c760c21a5d1f85bfc19e179b37d56f67”

category_active_record_relation {"id"=>["2", "3"]}

发布 {"post_name"=>"Test post", "post_type"=>"blogpost", "post_title"=>"Postie", "slug"=>"这是自定义设置 slug", "post_date"=>"2015 -06-30", "post_content"=>"Lorem ipsum dolor sit amet consequtiv", "post_excerpt"=>"Lorem ipsum", "post_status"=>"published", "comment_status"=>"closed", "comment_count "=>"0"}

save_and_continue "保存并继续"

【问题讨论】:

    标签: ruby activerecord nested-attributes padrino fields-for


    【解决方案1】:

    我已经设法回答了我自己的问题,解决方案相当简单,但也许有更好的解决方案,更神奇。无论如何,使用 CollectionProxy API 文档,很明显我可以在控制器中分配这些类别。

    admin/controllers/posts.rb

    只在 if @post.save 之前包含

     params[:category_active_record_relation]['id'].each do |category|
        category = Category.find(category)
        @post.categories << category
    end
    

    如果我要创建新类别,则可以使用 @post.categories.build(category) 方法。

    希望它也能帮助其他人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多