我想使用 .find() 和 Ruby on Rails 返回单个结果 [英] I want to return a single result using .find() with Ruby on Rails

查看:47
本文介绍了我想使用 .find() 和 Ruby on Rails 返回单个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户视图和一个租赁视图.在我的租赁视图中,我试图显示当前用户名.我想我已经很接近了,但我无法解决最后一点.

I have a user view and a rental view. In my rental view im trying to show the current users name. I think I am pretty close but I can't work out this last bit.

这将返回选择列表中的所有用户

This returns all of my users in a select list

<%= f.select :user_id, User.find(:all).collect {|t|
    [t.user_name, t.id]} %>

这将返回我当前的用户 ID

This returns my current users ID

<%= f.number_field :user_id %>

所以我想我可以做类似的事情

So I thought I could do something like

<%= f.select :user_id, User.find(:user_id).collect {|t|
    [t.user_name, t.id]} %>

我只想在选择列表中返回当前用户,并将他们的 id 作为值和他们在列表中的名称.如果我做了上面的事情,它会告诉我

Which I would want to only return the current user in a select list with their id as the value and their name in the list. If I do the above it tells me

Couldn't find User with id=user_id

所以 user_id 作为文字字符串传递,但我想传递 user_id 变量,它应该是 10 之类的东西.我不知道如何将 user_id 作为变量传递.

So user_id is being passed as a literal string but I want to pass the user_id variable which should be somthing like 10. I don't know how to pass the user_id as a variable.

我对 ROR 还很陌生,我可能会以完全错误的方式处理这个问题.非常感谢任何帮助.

I'm fairly new to ROR, I might be going about this the completely wrong way. Any help is much appreciated.

推荐答案

我假设您有一个租用对象,您为其显示表单,我假设它是一个实例变量 @rental,此外,我假设在您的 Rental 类中存在以下关系

I am assuming you have a rental object, for which you show the form, I assume it is an instance variable @rental, furthermore I assume that inside your Rental class there is the following relation

class Rental

  belongs_to :user

end

然后你可以写如下:

f.select :user_id, [[@rental.user.user_name, @rental.user.id]]

希望这会有所帮助.

关于一个相关但不太重要的说明:为 user 设置一个名为 user_name 的列真的很奇怪:我会将该列称为 name,因为它无论如何都是用户的一部分.

On a related but less important note: it is really weird to have a column called user_name for a user: I would call that column just name, since it is part of a user anyway.

这篇关于我想使用 .find() 和 Ruby on Rails 返回单个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆