简体   繁体   English

Rails:如何将字符串表示形式保存回模型中?

[英]Rails: How do I save a string representation back into a model?

I have an Employee model that has a SecurityClearanceLevel . 我有一个具有SecurityClearanceLevelEmployee模型。 When you make a new employee, you're asked to set a SecurityClearanceLevel by choosing from a <select> list. 当您结交新员工时,系统会要求您从<select>列表中进行选择来设置SecurityClearanceLevel The problem is that when I save the object, it's a string, not a SecurityClearanceLevel , so the save fails. 问题是,当我保存对象时,它是一个字符串,而不是SecurityClearanceLevel ,因此保存失败。

Where do I take care of this kind of back-and-forth conversion, and what's the best way to do it? 我该在哪里进行这种来回转换,最好的方法是什么?

Rails gives you a few variations around doing this. Rails为您提供了一些执行此操作的变体。 You should be able to do something like this: 您应该能够执行以下操作:

<%= collection_select(:employee, :security_clearance_level_id,
                      SecurityClearanceLevel.all, :id, :name) %>

Take a look at the Rails Guide on the select and option tags for the full details. 查看select和option标签上Rails Guide,以获取全部详细信息。

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

相关问题 如何从Rails中的模型保存 - how do I save from a model in rails Rails Model 中发生回滚时如何保存记录 - How do I save record when rollback happens in Rails Model 如何从 Rails 中的 model 方法保存到数据库 - How do I save to database from a model Method in rails 如何在Rails模型中render_to_string? - How do I render_to_string in a rails model? 我如何创建在最终保存到Rails中的create方法之后运行的回调? - How do I create a call back which runs after the final save in the create method in Rails? 我如何回滚这个 Rails 迁移? - How do i roll back this rails migration? 我该如何在用户搜索事件并保存感兴趣的事件的地方建模我的Rails应用程序? - How do I model my Rails application where users search for events and save the ones that interest them? Rails:如何在我的模型中调用`self.save`并将其保留在数据库中? - Rails: How do I call `self.save` in my model and have it persist in the database? Rails:如何将来自模型中的 before_save 的错误添加到控制器中? - Rails: How do I add into the controller an error that comes from a before_save in the model? Rails —如何从after_save回调中查看新旧模型的值? - Rails — How do I see old and new model values from an after_save callback?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM