我正在創建基本的留言板,其中許多評論屬於帖子,而帖子只屬於一個主題。我的問題是,我不確定如何從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
再次感謝。