我想基于当前的user.id == company.user_id访问show page,我想只显示特定用户添加的公司详细信息,当company_path链接点击时。
companies_controller.rb文件是
class CompaniesController < ApplicationController
def index
@companies = Company.all
end
def show
@company = Company.where(user_id:company.user_id)
@company_user_id = current_user.id
end
def company_params
params.require(:company).permit(:c_name, :c_description)
end
def find_company
@company = Company.find(params[:id])
end
end
routes.rb文件为
Rails.application.routes.draw do
devise_for :users
resources :jobs
resources :companies
root 'jobs#index'
end
rake路线信息为,
DELETE /jobs/:id(.:format) jobs#destroy
user_companies GET /users/:user_id/companies(.:format) companies#index
POST /users/:user_id/companies(.:format) companies#create
new_user_company GET /users/:user_id/companies/new(.:format) companies#new
edit_user_company GET /users/:user_id/companies/:id/edit(.:format) companies#edit
user_company GET /users/:user_id/companies/:id(.:format) companies#show
PATCH /users/:user_id/companies/:id(.:format) companies#update
PUT /users/:user_id/companies/:id(.:format) companies#update
DELETE /users/:user_id/companies/:id(.:format) companies#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
root GET / jobs#index
答案 0 :(得分:0)
您应该将公司资源包装在用户资源中:
Rails.application.routes.draw do
resources :users do
resources :companies
end
end
答案 1 :(得分:0)
将show action修改为
def show
@company = Company.find_by_user_id(current_user.id)
@company_user_id = current_user.id
end
并将您的路线修改为
Rails.application.routes.draw do
devise_for :users
resources :jobs
resources :companies, except: :show do
get :show, on: :collection, as: :show
end
root 'jobs#index'
end
而不是关注
<%= link_to "Companies", company_path(@company) %>
使用路径
<%= link_to "Companies", show_companies_path %>
我希望这会对你有帮助!!!
答案 2 :(得分:0)
show方法不应该显示给很多公司。您应该使用索引方法。
最好的选择是将公司定义为用户的嵌套资源(如eugene建议的那样)。
def index
if params[:user_id] && @user = User.find_by(id: params[:user_id])
@companies = @user.companies
else
@companies = Company.all
end
end
然后,在控制器中:
<%= link_to "View companies", user_companies_path(@user.id) %>
在视图中,要调用索引,您应该
!Sub arn:aws:kinesis:${AWS::Region}:${AWS::AccountId}:stream/xxxx
这将在@user中显示用户的公司。如果要显示current_user公司,只需将@user替换为current_user
即可