我正在研究多态活动Feed,并尝试将来自不同模型的Feed项目混合在一个页面中。
我有以下模型
Feed项目包括
模型关系
class User < ActiveRecord::Base
has_one :dashboard
has_many :activities
has_many :works
has_many :projects
has_many :project_records
end
class Work < ActiveRecord::Base
belongs_to :user
end
class Project < ActiveRecord::Base
belongs_to :user
has_many :project_records
end
class Dashboard < ActiveRecord::Base
belongs_to :user
has_many :activities
end
class Activity < ActiveRecord::Base
belongs_to :user
belongs_to :subject, polymorphic: true
end
我在用户模型中定义了Feed,用户可以关注其他Feed。
def feed
following_ids = "SELECT followed_id FROM user_followings
WHERE follower_id = :user_id"
Activity.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
end
要构建多态活动Feed,我在工作,项目, ProjectRecord 模型中有“after_create”。
after_create :create_activity
private
def create_activity
Activity.create(
subject: self,
user: user
)
end
end
然后,我尝试在信息中心(控制台)/ show(操作)页面中列出供稿(工作,项目,项目记录)
这是我的仪表板控制器
class DashboardsController < ApplicationController
before_action :authenticate_user!
before_action :only_current_user
def show
@feed_items = current_user.feed.order(created_at: :desc)
end
private
def only_current_user
@user = User.find( params[:user_id] )
redirect_to(root_url) unless @user == current_user
end
end
在仪表板/显示视图中
<% if @feed_items.any? %>
<div class="feed-listing">
<% @feed_items.each do |feed| %>
<% if feed.subject_type == 'Work' %>
<%= link_to polymorphic_path(feed.subject) do %>
<%= render "activities/work_feed", subject: feed.subject, :feed => feed %>
<%#= feed.subject.title %>
<% end %>
<% elsif feed.subject_type == 'Project' %>
<%= link_to polymorphic_path(feed.subject) do %>
<%= render "activities/project_feed", subject: feed.subject, :feed => feed %>
<% end %>
<% else %>
<%= link_to polymorphic_path(feed.subject) do %>
<%= render "/activities/project_record_feed", subject: feed.subject, :feed => feed %>
<% end %>
<% end %>
<% end %>
</div>
<% end %>
我收到错误消息“未定义的方法`project_record_path”#&lt;#:0x007f9368c63f88&gt;“
我知道路径错误,因为ProjectRecord属于Project。
我尝试使用“project_project_record_path”替换“polymorphic_path(feed.subject)”,但找不到project_id和project_record的id。
new_project_project_record GET /projects/:project_id/project_records/new(.:format) project_records#new
edit_project_project_record GET /projects/:project_id/project_records/:id/edit(.:format) project_records#edit
project_project_record GET /projects/:project_id/project_records/:id(.:format) project_records#show
如果我删除了link_to帮助程序(project_record),只能删除
<%= render "/activities/project_record_feed", subject: feed.subject, :feed => feed %>
,仪表板/显示页面显示,其他链接正常工作。
我希望每个ProjectRecord供稿链接到ProjectRecords / show页面 如何使这项工作?
答案 0 :(得分:0)
要解决您的路由问题,您可以使用浅路径:
resources :projects do
resources :project_records, shallow: true
end
这使得index
/ new
/ create
操作保持嵌套在Project
内,但show
/ update
/ destroy
转到顶层,就好像资源没有嵌套一样。