【发布时间】:2011-08-13 12:03:58
【问题描述】:
我正在创建基本的留言板,其中许多 cmets 属于一个帖子,而一个帖子只属于一个主题。我的问题是我不确定如何从Post 模型的表单创建一个新的Topic。我的 Post 控制器出现错误:
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'
app/controllers/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
再次感谢。
【问题讨论】:
标签: ruby-on-rails ruby forms methods controller