我有一个用户表和一个连接表的应用程序(把连接想象成朋友; user_id = current_user和otheruser_id =你正在查看的用户配置文件)。我在用户配置文件上有一个链接,让current_user编辑该连接。下面是用户展示页面上的form_for: (更新后的代码):Rails的ActiveRecord :: RecordNotFound
<% unless current_user == @user %>
<% if @connection.blank? %>
How do you know <%= @user.first_name %>? (<%= link_to "edit contact", { :controller => 'connections', :action => 'create', :id => :connection } %>)
<% else %>
<%= @user.first_name %> is your <%= @connection.description %> (<%= link_to "edit contact", { :controller => 'connections', :action => 'edit', :id => @connection.id } %>)
<% end %>
但是,单击上方编辑链接显示了这个错误:
的ActiveRecord :: RecordNotFound在ConnectionsController#编辑 Couldn '找到连接id = 2 [WHERE“connections”。“user_id”= 1]
看起来好像在显示页面上使用user_id(在上面的示例中,我正在查看user_id 2)作为连接表中的connection_id。我如何将其更改为正确的ID?如果需要的话
class ConnectionsController < ApplicationController
def update
@connection = current_user.connections.find(params[:id])
if @connection.update_attributes(params[:connection])
flash[:notice] = "Contact relationship updated"
redirect_to @user
end
end
def edit
@connection = current_user.connections.find(params[:id])
redirect_to @user
end
def create
#@user = User.find(params[:user_id])
@connection = current_user.connections.build(params[:connection])
if @connection.save
flash[:success] = "Contact relationship saved!"
redirect_to @user
else
render @user
end
end
end
用户控制器:
连接控制器
def show
@user = User.find(params[:id])
@connection = current_user.connections.build(:otheruser_id => @user)
end
怎样才可以有编辑和创建链接使用正确的CONNECTION_ID代替USER_ID的?
另外,我注意到的另一个问题是,该应用程序绕过if语句中的第一个条件。即使没有@connection,它也会跳到假设有是连接的情况。
您的时间非常感谢。我真的被困在这里。谢谢!
EDIT 1:添加路由,以防万一:
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
end
编辑2:
只是为了澄清,在上述错误信息,我观看USER_ID = 2轮廓,但不进行连接现在存在(只是做了一个本地清除),所以我的观点应该显示链接到创建路径(新发现的问题)。无论如何,它似乎仍然使用user_id代替connection_id。即使连接已经存在,它应该会编辑id = 1的连接,而不是2.
感谢迄今为止所有人的帮助。 编辑3:我更新了上面的form_for。我现在有两个问题:“如果connection.blank”
形式是不承认的IF语句并且正在进入第二个条件:即使数据库中不存在连接,也要编辑连接。
当我点击编辑链接,即使连接不存在,我得到一个路由错误:没有路由匹配{:controller =>“connections”,:action =>“edit”,:id =>零}。同样,这可能是因为还没有连接。在解决此问题之前,我可能需要修复#1。
PS:我愿意付出解决方案......我完全难倒了!再次感谢迄今为止帮助过的所有人。
使用“的before_filter的authenticate_user!”在连接控制器,那么它不会绕过if条件,如果你没有登录,current_user是零。除非你使用to_params方法,否则不能改变编辑链接的默认映射。 – sunny1304
感谢您的回复。我在控制器中添加了上述错误。我更新了我的问题以澄清错误。 – winston