2011-08-25 73 views
6

我有一個location模型和一個post模型。我希望允許用戶從location模型的index頁面創建新的posts。我怎麼做?我試圖將postnew.html.erb作爲locationindex.html.erb中的一部分進行渲染,但這會導致錯誤,因爲postnew.html.erb引用了@post變量。Rails:從視圖中的不同模型中顯示錶格

我該如何做到這一點?

回答

14

嘗試是這樣的

LocationController 

def index 
    @location = Location.find(:all) 
    @post = Post.new 
end 

現在烏爾位置視圖將有機會獲得實例變量@post。使用

render :partial => 'posts/post', :object => @post 
+0

+1,..或者類似於Allesklar提出的方式:使用Post.new而不是變量,但這取決於視圖:變量可能在那裏被'硬編碼'。 – Arsen7

0

只需在LocationsController的操作中創建一個@post變量。

+0

這給了我這個錯誤渲染的部分:'預計/home/eyekandy/rails_apps/eyekandy/app/controllers/locations_controller.rb定義LocationsController' –

+0

然後你有**語法錯誤**在你的代碼中。你能展示你的行爲代碼嗎?我假設你只編輯了動作,但錯誤可能在其他地方 - 也許你不小心刪除了一些字符? – Arsen7

3

可以啓動形式是這樣的:

<%= form_for Post.new do ... %> 
相關問題