link_to issue with inherited Active Record class

妖精的绣舞 提交于 2019-12-11 02:25:17

问题


Here are the classes as I have them set up:

class Stat < ActiveRecord::Base
    belongs_to :stats_parent
end

class TotalStat < Stat
    belongs_to :stats_parent
end

#The StatsParent class is just to show how I use the relation.
class StatsParent < ActiveRecord::Base
    has_one  :total_stat
    has_many :stats
end

For the Stats Controller index action:

def index
    @stats = Stat.all
    respond_to do |format|
        format.html # index.html.erb
        format.xml  { render :xml => @stat }
    end
end

In the index view for stats there is this bit of code:

<% @stats.each do |stat| %>
    ...
    <td><%= link_to 'Show', stat %></td>
<% end %>

And I get this error:

undefined method `total_stat_path' for #<ActionView::Base:0x0000010324c1f8>

Why cant the link_to work here? Do I need to create a separate controller to handle the TotalStat?


回答1:


There's clearly an STI(single table inheritance) issue there, though I'd need to see more code to see what's really up. A quick fix would be to be more specific about the link_to path:

<%= link_to "Show", stat_path(stat) %>


来源:https://stackoverflow.com/questions/1773367/link-to-issue-with-inherited-active-record-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!