2014-09-13 132 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