2014-05-19 182 views
0

我把所有的代碼在這個要點,因爲我不能讓格式工作。與Rails的ActiveRecord關係的麻煩,並在另一個模型視圖內添加一個模型的記錄

https://gist.github.com/anonymous/72e66308c236a0277943

我所試圖做的是對的教授頁面上prof_comments模型的形式。

每當我嘗試,並提交我公司目前擁有的prof_comments模型的形式,它會嘗試張貼到目前的教授展示頁面(/教授/ 1)

我一直在試圖遵循以下的StackOverflow職位,但沒有運氣。

Rails: Show form from different model in a view

Possible to add a form into another models view in rails

的routes.rb

Rails.application.routes.draw do 


    root :to => "welcome#index" 
    devise_for :users 
    resources :users 

    resources :professors 
    resources :prof_comments 
    resources :classes 
    resources :class_comments 

end 
+0

所以你想讓prof_comments出現在教授的'show page'下?像帖子和嵌套評論?請詳細解釋。另外,發佈你的'routes.rb' –

+0

是的,我想要一個表單來爲該教授在其顯示頁面下添加一個新的prof_comment。我剛剛添加routes.rb。 – Zeratas

回答

1

我不確定你正在嘗試的方法,但這將完成你想要做的事情:讓教授的評論出現在它的show頁面下。

您可以在professors

你擊潰窩prof_comments看起來就像這樣:

resources :professors do 
    resources :prof_comments, shallow: true 
end 

prof_comments controller

def create 
    @professor = Professor.find(params[:id]) #this pulls specific professor by :id 
    @prof_comment = @professor.prof_comments.create(prof_comment_params) 
    redirect_to professor_path(@professor) # this will rout you to professor's show page once the comment is created. 
    end 
end 

app/views/professors/show.html

h2>Add a comment:</h2> 
    <%= form_for([@professor, @professor.prof_comments.build]) do |f| %> 

    <%= f.label :commenter %><br> #commenter with the actual attribute_name 
    <%= f.text_field :commenter %> #commenter with the actual attribute_name 

    <%= f.label :body %><br> #body should be replaced with your actual attribute_name 
    <%= f.text_area :body %> #body should be replaced with your actual attribute_name 

    <%= f.submit %> 

<% end %> 

這些評論將出現在professor show視圖下。評論嵌套在它下面。像往常一樣對待教授的控制者。您將使用prof_comments控制器來創建註釋。

+0

中獲得professor_id,我將不得不嘗試兩種方法。我想我現在會接受你的,因爲它看起來更加充實。 IT也看起來更集中於將它們連接在一起。謝謝! – Zeratas

+1

順便說一句,你可以移動評論表單到一個部分,並渲染它以避免混亂。順便提一下,這種方法來自[rails guides tutorial](http://guides.rubyonrails.org/getting_started.html)。它會引導你通過它 –

1

你必須使用

form_for @prof_comment 

與@不:

+0

我想我明白了。 @prof_comment意味着我引用了我在show路徑下的控制器中定義的prof_comment實例? – Zeratas

+0

這裏的差異很好的解釋http://stackoverflow.com/questions/2006329/ruby-on-rails-symbol-as-argument-in-form-for – Iceman

+0

好的。所以看起來我的下一個問題是將教授ID發送給prof_comments控制器。這會很有趣。 – Zeratas

相關問題