简体   繁体   English

Rails - 将变量传递给字符串插值

[英]Rails - passing a variable to string interpolation

This is what's in my controller.这就是我的控制器中的内容。 I'm using devise and I'm trying to show take the user email and pass it into a where to find the specific family so I can display just the unique family controlled by the user.我正在使用设计,我试图显示接收用户电子邮件并将其传递到查找特定家庭的位置,以便我可以仅显示由用户控制的唯一家庭。

I'm having an issue with the string interpolation.我在字符串插值方面遇到了问题。 If I hard code the email into the query it works fine.如果我将电子邮件硬编码到查询中,它就可以正常工作。 But I want it to be dynamic.但我希望它是动态的。 Thanks for the help!感谢您的帮助!

home_controller.rb

  user_email = current_user.email
  @unique_family = Unit.where(:accountOwner => '#{user_email}')

For string interpolation you need to use double quotes "" , like:对于字符串插值,您需要使用双引号"" ,例如:

name = 'Some name'
puts "Hello #{name}"
# => "Hello Some name"

You see there name is defined within single quotes, but using the puts and interpolating the "Hello" string with the name variable, then is necessary to use double quotes.您会看到name在单引号内定义,但是使用 puts 并使用name变量插入“Hello”字符串,则需要使用双引号。

To make your where query you can try with:要进行where查询,您可以尝试:

user_email = current_user.email
@unique_family = Unit.where(:accountOwner => user_email)

In such case isn't necessary to interpolate your user_email with "nothing" or trying to convert it to string, unless you want to make sure what's being passed will be an string, so you could do:在这种情况下,没有必要使用“nothing”插入user_email或尝试将其转换为字符串,除非您想确保传递的内容是字符串,因此您可以执行以下操作:

@unique_family = Unit.where(:accountOwner => user_email.to_s)

Or better:或更好:

@unique_family = Unit.where('accountOwner = ?', user_email)

That will bind the passed value for user_email to your query.这会将传递的user_email值绑定到您的查询。

Just use the normal where method:只需使用正常的where方法:

user_email = current_user.email
@unique_family = Unit.where(accountOwner: user_email)

I'd suggest you create association User <=> Unit , something like我建议您创建关联User <=> Unit ,例如

in user.rb在用户.rb

has_one :family, class_name: Unit, foreign_key: :email

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

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