发送电子邮件,ID未通过

时间:2015-11-13 14:37:11

标签: ruby-on-rails email

我有一页

http://localhost:3000/email/correspond?id=6

这是发送电子邮件的表单。发送后,它将更改为:

http://localhost:3000/email/correspond

并抛出错误; Couldn't find User with 'id'=这是由

引起的
def set_user
  @user = User.find(params[:id])
end

位于email_controller中(见下文)

我无法理解这个问题,因为ID是在发送网址中给出的。

任何人都可以解释一下吗?

来自email_controller.rb

`

def correspond
  @cuser = @current_user
  @recipient  = @user
  @title = "Email" 
  if param_posted?(:message)
    @message = Message.new(params[:message])
    if @message.valid?
      PostMailer.say_hello(@cuser, @recipient, @message).deliver_now
      flash[:notice] = "Email sent."
      redirect_to user_path(@recipient)
    end
  end
end

def set_user
  @user = User.find(params[:id])
end` 

的routes.rb

Eskvalleytales::Application.routes.draw do
  root :to => 'users#index'

  get 'user/:id' => 'user#show'
  get 'user/search' => 'user#search'
  resource :sessions
  get 'session/destroy' => 'sessions#destroy'
  get 'friendship/accept' => 'friendship#accept'
  get 'friendship/decline' => 'friendship#decline'
  get 'friendship/cancel' => 'friendship#cancel'
  get 'friendship/delete' => 'friendship#delete'
  get  'friendship/create' => 'friendship#create'
  get  'email/correspond' =>  'email#correspond'
  post 'email/correspond' => 'email#correspond'
  resources :comments
  resources :users
  resources :subcomments
  resources :profiles
  resources :emails
  resources :users do   
    resources :comments do
      resources  :subcomments
    end
  end
  resources :comments do  
    resources :subcomments
  end
  resources :users do
    resources :emails
    resources :new_file
  end

  resources :users do
    resources :emails do
    end
  end

  resources :users do  
    resources :fiendships
  end

  resources :users do  
    resources :subcomments
  end
end

2 个答案:

答案 0 :(得分:0)

首先,您不需要重定向相同的操作。如果您仍然需要在set_user method中进行简单的ID检查。喜欢以下

def set_user
  @user = User.find(params[:id]) if params[:id]
end

答案 1 :(得分:0)

routes.rb开始,您有:

post 'email/correspond' => 'email#correspond'

这是您发送表单时所拥有的路径(网址)的责任:http://localhost:3000/email/correspond

但是,您有兴趣将id与请求一起发送为params/:id),而不是query?id=:id) ,因为你是从电子邮件控制器内部寻找的。

要实现这一目标,您必须配置路线以获取给定的id,如下所示:

post 'email/correspond/:id' => 'email#correspond'

执行此操作可确保将ID作为参数发送,然后在您拨打set_user

def set_user
   @user = User.find(params[:id])
end

User.find(params[:id])查看请求的参数内部,并取/:id处的任何内容。

示例:

"http://localhost:3000/email/correspond/6"发布的帖子请求params[:id] => 6