如何link_to从Feed更正显示页面?

时间:2015-05-31 22:31:13

标签: ruby-on-rails ruby

如果用户点击:

活动/估值/ _create.html.erb

<%= link_to valuation_path(activity) do %>
  <%= activity.trackable.name %>
<% end %>
例如,他被引导到错误:

  

找不到带有&#39; id&#39; = 24

的估价值

因为估值实际为7.这是因为这行代码试图通过将ID号作为活动而不是id号作为估价来查找估价显示页面。

为了解决这个问题,我试过了:

<%= link_to valuation_path(@valuation) do %>
  <%= activity.trackable.name %>
<% end %>

但是会出错:

  活动#index

中的ActionController :: UrlGenerationError      

没有路线匹配{:action =&gt;&#34; show&#34;,:controller =&gt;&#34;估价&#34;,   :id =&gt; nil}缺少必需的键:[:id]

我们如何重写代码以使用户获得正确的估值显示页面?

activities_controller

class ActivitiesController < ApplicationController
    def index
        @activities = Activity.order("created_at desc").paginate(:page => params[:page])
    end

    def show
          redirect_to(:back)
    end

  def like
    @activity = Activity.find(params[:id])
    @activity_like = current_user.activity_likes.build(activity: @activity)
    if @activity_like.save
      @activity.increment!(:likes)
      flash[:success] = 'Thanks for liking!'
    else
      flash[:error] = 'Two many likes'
    end  
      redirect_to(:back)
  end
end

activity.rb

class Activity < ActiveRecord::Base
  self.per_page = 20
  has_many :notifications
  belongs_to :user
  belongs_to :trackable, polymorphic: true

  def conceal
    trackable.conceal
  end

  def page_number
    (index / per_page.to_f).ceil
  end

private

  def index
    Activity.order(created_at: :desc).index self
  end
end

活动/索引

<% @activities.each do |activity| %>
    <%= link_to activity.user.name, activity.user %></b>
    <%= render "activities/#{activity.trackable_type.underscore}/#{activity.action}", activity: activity %>
<% end %>

1 个答案:

答案 0 :(得分:1)

好像你想做一个嵌套资源,

当你有activities/valuations/_create.html.erb时,这意味着你应该有一个嵌套路线

#routes.rb
resources :activities do
  resources :valuations
end  

所以你的链接应该是

<%= link_to 'link', activities_valuataions_path(activity, @validation) %>

如果你可以张贴你的路线

rake routes

应该很容易找到问题