[英]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.