繁体   English   中英

无法访问变量

[英]Can't Access Variables

我有一个Request模型,用于存储性别,适合水平和一个人的可用性。 该对象属于用户模型。 我想要做的是将最初发出请求的用户的用户ID传递给,然后在用户单击按钮时将:user参数发送到邮件控制器上的send_mail操作。 这不起作用,Rails说出了意外的关键字。 我基本上是试图将Request对象的user.id传递给邮件控制器send_email操作。 在这里它将使用user_id查找用户,然后从那里找到该用户的电子邮件。 然后,我将向用户发送包含此变量的电子邮件。

请求控制器

class RequestsController < ApplicationController
before_action :authenticate_user!

def index
    @requests = Request.all
end

def create
    @request = Request.new(request_params)
    @request.user = current_user
    @request.save
    redirect_to requests_path 
end

def new
    @request = Request.new
end

def destroy
end

private 
    def request_params
        params.require(:request).permit(:gender, :level, :time_available)
    end
end

Index.html.erb

<% provide(:title, "Open Requests") %>
<table class="table table-hover">
  <th>Gender</th>
  <th>Level</th>
  <th>Time Available: </th>
  <% @requests.each do |request| %>
  <tr>
    <td><%= request.gender %></td>
    <td><%= request.level %></td>
    <td><%= request.time_available %></td>
    <td><%= button_to "I want to exercise with you!", {:controller => "mail", :action => "send_email", :user => Request.user }  class: "btn btn-primary" %></td>
  </tr>
<% end %>
</table>

邮件控制器

class MailController < ApplicationController
    def send_email
        @creation_user = :user
        @email = @creation_user.email
    end
end

Send_Email.html.erb

<h2><%= @email %></h2>

在您的情况下,您需要从params哈希中提取用户:

def send_email
  @creation_user = params[:user]
  @email = @creation_user.email
end

更新:

您应该定义一个嵌套资源

配置/ routes.rb中

resources :requests, only: [:index, :new, :create] do
  resources :mails, only: [:create]
end

现在更新您的视图以使用新路线。

应用程序/视图/请求/ index.html.erb

<%= button_to "I want to work out with you!", request_mails_path(request) %>

更新您的控制器。

应用程序/控制器/ mails_controller.rb

def create
  @email = user.email
end

private

def user
  find_request.user
end

def find_request
  Request.find(params[:request_id])
end

将您的视图send_email.html.erb重命名为create.html.erb

只需将user传递给函数即可尝试

 class MailController < ApplicationController
    def send_email
        @creation_user = params[:user]
        @email = @creation_user.email
    end
end

在路由中config/routes.rb

get "mail/send_mail", to: 'mail#send_mail'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM