2012-10-26 221 views
1

我真的是Ruby on Rails中的新手... 我試圖在我的項目中創建另一個頁面的鏈接,其中列出了屬於escuela的帖子。在Ruby on Rails中創建鏈接

這是我做過什麼:

在posts_controller.rb我寫道:

def postesc 
    @posts = Post.where(:escuela_id => params[:id]) 
    respond_to do |format| 
     format.html # postesc.html.erb 
     format.json { render json: @posts } 
    end 
    end 

在配置/ routes.rb中我寫道:

match 'postesc' => 'posts#postesc' 

鑑於/ escuelas/listaesc .html.erb我寫了鏈接:

<%= link_to "Escuelas", :controller => "posts", :action => "postesc" %> 

並在視圖/ escuelas/postesc.html.erb我想列出匹配的帖子。 但是這個頁面只顯示空白,只有佈局。

請幫忙嗎?

回答

0

使routes.rb中的變化進行

得到 'postesc'=> '的帖子#postesc'

嘗試... <%=的link_to 「Escuelas」,postesc_path%>

OR

<%= link_to "Escuelas", { :controller => "posts", :action => "postesc" } %> 
0

你錯過添加一個ID爲埃斯庫埃拉被選擇 - 因爲你在你的控制器#postesc行動做(如文字:其中:escuela_id => PARAMS [:編號]) 。

<%= link_to "Escuela", :controller => "posts", :action => "postesc", :id => 1 %> 

,但你可以使用下面的語法(通過改變你的路由豆蔻)使用對象的鏈接方法:

# in routes.rb 
match 'postesc' => 'posts#postesc', on: :collection, as: 'esc_index' 

# in your view 
<%- for escuela in @escuelas do %> 
    <%= link_to "Escuela", esc_index(escueal) %> 
<% end %> 
2

首先要交和ESCUELA之間的關聯,那麼你就可以找到它只是

Escuela.find(params[:id]).posts 

你的路線更改爲 -

resources :posts do 
    get 'postesc', :on => :collection 
end 

查看:

<%= link_to "List posts", postesc_posts_path %>