2011-04-27 148 views
1

我正在创建基本的留言板,其中许多评论属于帖子,而帖子只属于一个主题。我的问题是,我不确定如何从Post模型的表单创建新的Topic。我在我的帖子控制器接收到错误:是什么导致了这种AssociationTypeMismatch错误?

ActiveRecord::AssociationTypeMismatch in PostsController#create 

Topic(#28978980) expected, got String(#16956760) 

app/controllers/posts_controller.rb:27:in `new' 
app/controllers/posts_controller.rb:27:in `create' 

应用程序/控制器/ posts_controller.rb:27:

@post = Post.new(params[:post]) 

这里是我的模型:

topic.rb:

class Topic < ActiveRecord::Base 
    has_many :posts, :dependent => :destroy 
    validates :name, :presence => true, 
        :length => { :maximum => 32 } 
    attr_accessible :name 
end 

post.rb:

class Post < ActiveRecord::Base 
    belongs_to :topic, :touch => true 
    has_many :comments, :dependent => :destroy 
    attr_accessible :name, :title, :content, :topic 
    accepts_nested_attributes_for :topics, :reject_if => lambda { |a| a[:name].blank? } 
end 

comment.rb:

class Comment < ActiveRecord::Base 
    attr_accessible  :name, :comment 
    belongs_to :post, :touch => true 
end 

我有一个表格:

<%= simple_form_for @post do |f| %> 
    <h1>Create a Post</h1> 
    <%= f.input :name %> 
    <%= f.input :title %> 
    <%= f.input :content %> 
    <%= f.input :topic %> 
    <%= f.button :submit, "Post" %> 
<% end %> 

而且它的控制器动作:(帖子创建)

def create 
    @post = Post.new(params[:post]) # line 27 
    respond_to do |format| 
    if @post.save 
     format.html { redirect_to(@post, :notice => 'Post was successfully created.') } 
    else 
     format.html { render :action => "new" } 
    end 
    end 
end 

在所有我找实例,标签属于帖子。我正在寻找的是不同的,可能更容易。我想要一个帖子属于一个标签,Topic。我如何通过Post控件创建主题?有人能指引我朝着正确的方向吗?非常感谢您阅读我的问题,我非常感谢。

我正在使用Rails 3.0.7和Ruby 1.9.2。哦,这里是我的模式以防万一:

create_table "comments", :force => true do |t| 
    t.string "name" 
    t.text  "content" 
    t.integer "post_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

create_table "posts", :force => true do |t| 
    t.string "name" 
    t.string "title" 
    t.text  "content" 
    t.integer "topic_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

create_table "topics", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

再次感谢。

回答

0

@post = Post.new(params[:topic])在我的控制器中修复了错误。

1

你应该有:

accepts_nested_attributes_for :topic 

Post,而不是周围的其他方式。

相关问题