我仍然是rails的新手,我试图找出如何在不使用嵌套路由或表单的情况下实现多态关联。我尝试搜索,但似乎所有内容都是关于嵌套表单或添加注释,这不是我想要做的。
以下是我的模特
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
我想在“组织”或“人物”展示页面中实施“新文章”链接,并输入正确的article_id
和article_type
。生成此链接的正确语法是什么?
谢谢!
答案 0 :(得分:0)
路线:
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
组织观点:
link_to new_organization_article_path(@organization)...