在Ruby on Rails中建立链接

时间:2012-10-26 11:09:12

标签: ruby-on-rails

我真的是Ruby on Rails中的新手...... 我正在尝试在我的项目中建立另一个页面的链接,其中列出了属于escuela的帖子。

这就是我所做的:

在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

在config / routes.rb中我写道:

match 'postesc' => 'posts#postesc'

在view / escuelas / listaesc.html.erb中我写了链接:

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

在view / escuelas / postesc.html.erb中我想列出匹配的帖子。 但是这个页面只显示空白,只有布局。

请帮忙吗?

3 个答案:

答案 0 :(得分:2)

首先在post和escuela之间建立关联,然后你可以通过

找到它
Escuela.find(params[:id]).posts  

将路线更改为 -

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

查看:

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

答案 1 :(得分:0)

将routes.rb更改为

获取'postesc'=&gt;的帖子#postesc'

尝试...&lt;%= link_to“Escuelas”,postesc_path%&gt;

OR

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

答案 2 :(得分:0)

您缺少为Escuela添加ID以供选择 - 正如您在Controller#postesc Action中所做的那样(如文字:where:escuela_id =&gt; params [:id])。

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

但你可以使用以下语法使用object-link方法(通过改变你的路线):

# 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 %>