I am still new to rails and I am trying to figure out how to implement a polymorphic association without using a nested route or form. I tried searching but everything seemed to be about nesting forms or adding comments, which is not what I am trying to do.

Here are my models

Article.rb

class Article < ActiveRecord::Base
  belongs_to :articable, polymorphic: true
end

Organization.rb

class Organization < ActiveRecord::Base
  has_many :articles, as: :articable
end

People.rb

class People < ActiveRecord::Base
  has_many :articles, as: :articable
end

I want to implement a 'New Article' link from a Organization or People show page and have the correct article_id and article_type entered. What would the correct syntax be to generate this link?

Thanks!

有帮助吗?

解决方案

Routes:

resource :people do
  resource :articles
end

resource :organizations do
  resource :articles
end

ArticlesController:

def create
  article = Article.new(params[:article])
  if params[:people_id]
    people = People.find(params[:people_id])
    people.articles << article 
  else
    organization = Organization.find(params[:organization_id])
    organization.articles << article 
  end
  article.save  
end

Organizations view:

link_to new_organization_article_path(@organization)...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top