2014-09-13 128 views
0

我试图在同一视图中为两种不同模型制作两种形式。两种形式,两种模式,一种观点ROR

我有一个型号命名类别和型号命名后。 我试图在同一视图中为类别创建表单我有一个表单。 上岗的形式工作正常,但是当我尝试添加的形式类别我得到这个错误:类别:: ActiveRecord_Relation 未定义的方法`MODEL_NAME”:类

category.rb - 模型

has_many :posts

post.rb - 模型

has_many :categories

posts_controller

def index 
@posts = new.Post 
@categories = new.Category 
end 

def create 
@posts = Post.create(post_params) 
@posts.save 
redirect_to :back 
end 

def create_cate 
@categories = Categroy.create(categories_params) 
@categroies.save 
redirect_to :back 
end 

帖子查看 - index.html.erb

<%= form_for(@posts) do |f| %> 
<%= f.text_field :title %> 
<%= f.text_area :content %> 
<%= f.submit %> 
<% end %> 

<%= form_for(@categories) do |f| %> 
<%= f.text_field :name %> 
<%= f.submit %> 
<% end %> 

的routes.rb

resources :posts 
resources :categories 
root 'posts#index' 

我都试过后,如果进行搜索,但我只能找到解决方案两种模式,一种形式。

在此先感谢。 :-)

回答

3

既然你说,它在index动作:

def index 
    @post = Post.new 
    @category = Category.new 
end 

在你看来:

<%= form_for(@post) do |f| %> 
    <%= f.text_field :title %> 
    <%= f.text_area :content %> 
    <%= f.submit %> 
<% end %> 

<%= form_for(@category) do |f| %> 
    <%= f.text_field :name %> 
    <%= f.submit %> 
<% end %> 
+0

非常感谢。 :-) – niiicolai 2014-09-13 15:58:25

+1

这种方法根据[桑迪的规则]是错误的(* http://robots.thoughtbot.com/sandi-metz-rules-for-developers) - *控制器只能实例化一个对象。因此,视图只能知道一个实例变量,而视图只应该将消息发送到该对象。* – 2014-09-13 16:17:52

+0

听起来很有趣。我会详细阅读。谢谢:) – niiicolai 2014-09-13 17:34:28