简体   繁体   English

Rails 4强参数会议

[英]rails 4 strong params session

I am using a custom passwordless login for my app. 我正在为我的应用程序使用自定义的无密码登录名。 A user simply needs to enter their username or email, and then a unique login link with a token is sent to them. 用户只需要输入他们的用户名或电子邮件,然后向其发送一个带有令牌的唯一登录链接。 They enter their username or email into a simple form : 他们以简单的形式输入用户名或电子邮件:

<%= form_tag request_token_path, id:'login-form' do %>
     <%= text_field_tag :user_id %>
<% end %>

This posts to a sessions#request_token method which verifies whether that user exists and then sends along the login link. 这会发布到一个sessions#request_token方法中,该方法验证该用户是否存在,然后沿着登录链接发送。

def request_token
   lookup = session_params[:user_id]
   if lookup.include? '@'
     @user = User.find_by(email: lookup)
   else
     @user = User.cached_find(lookup)
   end
   if @user
     @user.send_login_link
     redirect_to login_path, notice: "#{@user.username.capitalize} your email was sent!"
   else
     redirect_to login_path, notice: "Whoops! Looks like #{lookup} is not registered on this site. Please check spelling or signup!"
   end
 end

My question is that in my SessionsController file I defined the sessions_params 我的问题是,在我的SessionsController文件中,我定义了sessions_params

private
def session_params
  params.require(:session).permit(:user_id,:auth_token)
end

I know that means that I have to use a session object or in order to pass along the :user_id from the form since I defined :user_id as a param that is on valid as an attribute of a session. 我知道这意味着我必须使用会话对象或从表单传递:user_id ,因为我将:user_id定义为有效的参数,作为会话的属性。 I am wondering the correct way to do this. 我想知道这样做的正确方法。 Making a new session object doesn't make sense since that isn't even a model I have but is it safe to just take it from the params? 制作一个新的会话对象没有意义,因为那甚至不是我所拥有的模型,但是从参数中获取它是否安全?

and instead make lookup = params[:user_id] ? 而是使lookup = params[:user_id]吗?

If you have a session object that responds to user_id attribute, you need to create the form for that object specifically: 如果您有一个响应user_id属性的会话对象,则需要专门为该对象创建表单:

<%= form_for @session do |f| %>
    <%= f.text_field :user_id %>
<% end %>

If that's not the case, and you need to stick to form_tag, try making the attribute name something that would come up in the controller as a session hash: 如果不是这种情况,则需要坚持使用form_tag,请尝试使属性名称成为会话哈希值在控制器中出现:

<%= text_field_tag "session[user_id]" %>

When you do 当你做

params.require(:session)

it means you're requiring your params hash to have a session key, which in turn should have the permitted user_id attribute: 这意味着您要求params哈希具有会话密钥,而会话密钥又应具有允许的user_id属性:

{params: {session: {user_id: "something"}}

And thats why you'd need form_for @session OR the textfield with the suggested "session[user_id]" name 这就是为什么您需要form_for @session或带有建议的“ session [user_id]”名称的文本字段的原因

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

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