【发布时间】: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