我在包含信用/编辑对象链接的页面上收到以下错误:
路由错误 没有路线匹配{:controller =>“connections”,:action =>“edit”,:id => nil}
我的应用拥有用户个人资料页面(users_controller.rb中的#show操作),其中包含创建或编辑现有“连接”的链接(Facebook或LinkedIn等用户之间的关系)。如果连接不存在,链接将发送用户创建新连接。如果连接已存在,则链接将发送用户编辑现有连接。我的创建功能很好。但是,一旦创建了连接,访问用户页面就会引发路由错误。它显然不喜欢我的link_to用于编辑操作。
以下是用户页面上的link_to:
<% unless current_user == @user %>
<% if @contact.present? %>
<%= @user.first_name %> is your <%= @connection.description %> (<%= link_to "edit contact", { :controller => 'connections', :action => 'edit', :id => @connection.id} %> )
<% else %>
How do you know <%= @user.first_name %>? (<%= link_to "edit contact", { :controller => 'connections', :action => 'create', :user_id => @user.id }, :method => 'post' %> )
<% end %>
该错误还明确指出:id设置为nil(null)。问题必须在这里。我的应用程序如何引用正确的连接?我的实例变量应该已经完成了这个技巧。
这是连接控制器:
class ConnectionsController < ApplicationController
def index
end
def update
@connection = current_user.connections.find(params[:id])
if @connection.update_attributes(params[:connection])
flash[:notice] = "Contact relationship updated"
render 'activities'
end
end
def edit
@connection = current_user.connections.find(params[:id])
end
def create
#@user = User.find(params[:user_id])
@connection = current_user.connections.build(params[:connection])
@user = User.find(params[:user_id])
if @connection.save
flash[:success] = "Contact relationship saved!"
else
render @user
end
end
end
这是User controller show action(link_to存在的地方):
def show
@user = User.find(params[:id])
@connection = current_user.connections.build(:otheruser_id => @user)
@contact = current_user.connections.where(user_id: current_user, otheruser_id: @user)
end
routes.rb中:
authenticated :user do
root :to => 'activities#index'
end
root :to => "home#index"
devise_for :users, :controllers => { :registrations => "registrations" }
resources :users do
member do
get :following, :followers, :posts, :comments, :activities, :works, :contributions, :connections
end
end
resources :works do
resources :comments
end
resources :relationships, only: [:create, :destroy]
resources :posts
resources :activities
resources :reposts
resources :comments do
member do
put :toggle_is_contribution
end
end
resources :explore
resources :connections
有关如何修复link_to的任何想法?谢谢!
编辑1:相关的佣金路线:
connections GET /connections(.:format) connections#index
POST /connections(.:format) connections#create
new_connection GET /connections/new(.:format) connections#new
edit_connection GET /connections/:id/edit(.:format) connections#edit
connection GET /connections/:id(.:format) connections#show
PUT /connections/:id(.:format) connections#update
DELETE /connections/:id(.:format) connections#destroy
答案 0 :(得分:1)
您的问题出在:
@connection = current_user.connections.build(:otheruser_id => @user)
实例化一个连接对象并将其分配给@connection。此对象尚未保存,因此它没有id。从概念上讲它也是错的,你怎么能编辑一些不存在的东西呢?如果您想要发送用户来创建新连接,那么Connections#new就是您所追求的。