f.select,传递一个id,但在Rails中显示一个名字

时间:2016-02-21 18:09:19

标签: ruby-on-rails

我需要一个表单,用户可以从列表中选择两个玩家(两个单独的选择字段)。 后来,在控制器中我需要找到那两个Player实例。 我知道在表单中传递对象的唯一方法是使用它的id,但我无法让用户选择原始数字 - 我希望能够向玩家展示'选择框中的名称,但以某种方式传递id。有可能吗?

1 个答案:

答案 0 :(得分:4)

您需要使用Rails options_for_select helper。此助手将在您的模型中向视图显示人类可读字段,同时通过 v3.hs:104:63: Couldn't match expected type ‘[Rating] -> Bool’ with actual type ‘Bool’ In the first argument of ‘(.)’, namely ‘((map fst ratings) /= newUser)’ In the first argument of ‘filter’, namely ‘(((map fst ratings) /= newUser) . ratings)’ In the second argument of ‘(.)’, namely ‘filter (((map fst ratings) /= newUser) . ratings)’ v3.hs:104:72: Couldn't match expected type ‘[(Char, b0)]’ with actual type ‘Film -> [Rating]’ Probable cause: ‘ratings’ is applied to too few arguments In the second argument of ‘map’, namely ‘ratings’ In the first argument of ‘(/=)’, namely ‘(map fst ratings)’ v3.hs:104:93: Couldn't match type ‘(String, Int)’ with ‘Film’ Expected type: Rating -> [Rating] Actual type: Film -> [Rating] In the second argument of ‘(.)’, namely ‘ratings’ In the first argument of ‘filter’, namely ‘(((map fst ratings) /= newUser) . ratings)’ 哈希从同一模型返回id字段。

params

您需要确保使用<%= f.select :user_id, options_for_select(@users.collect { | user | [user.name, user.id] }, @user.id), {}, {} %> 以与视图对应的控制器方法定义@users@user。您显然需要在User模型中同时使用options_for_selectid字段,否则,此帮助程序将失败。