Rails使用Polymorphic_url和STI在嵌套资源上生成错误的路径

时间:2019-04-13 16:09:23

标签: ruby-on-rails ruby

我的代码不是那么传统,我正在努力为资源生成正确的路径。

在我的路线上。rb

{
  let name = [ 'john', 'mark'];

  console.log(name);
  console.log(name[1]);
  console.log(name.length);
  
}

我的模特是:

Match.rb

namespace :admin do
  resources :matches do
    resources :lineups do
      resources :substitutions
    end
  end
end

在home_lineup.rb上获取STI结构

class Match < ApplicationRecord
  has_one :home_lineup
  has_one :away_lineup
end

在away_lineup.rb上的STI结构

class HomeLineup < Lineup

end

lineup.rb

class AwayLineup < Lineup

end

然后是替换。rb

class Lineup < ApplicationRecord
  belongs_to :match
  #has a :type column as :string
end

当我尝试:

class Substitution < ApplicationRecord
  belongs_to :lineup
end

我得到:

m = Match.last
l = m.home_lineup
s = Substitution.new
app.polymorphic_url([:admin, m, l, s])

但是我真正想要的是“ admin_match_lineup _...”。

我该怎么做才能解决此问题?

1 个答案:

答案 0 :(得分:0)

我在此博客文章(http://leomayleomay.github.io/blog/2014/03/24/customize-the-polymorphic-url-for-sti/)中找到了解决问题的方法。

要强制Lineup响应正确的名称,请在文件中添加以下代码:

lineup.rb

def self.model_name
  ActiveModel::Name.new(self, nil, "Lineup")
end

谢谢,祝您编程愉快。