RoR 查找示例
我有一个非常简单的问题,但找不到很好的解决方案。我在 ruby 中有一个查找代码(例如,住在某个州的学生):
# State lookup (id, name)
class State < ActiveRecord::Base
has_many :students
end
# Class that belogs to a state
class Student< ActiveRecord::Base
belongs_to :state
end
在 view/students/new.html.erb 视图中,我将各州显示为下拉列表:
<p>
<%= f.label :state %><br />
<%= f.collection_select :state, State.find(:all),
:id, :name, :prompt => "Select a State" %>
</p>
到目前为止,一切都很好,但是当我点击“保存”,出现错误:
State(#37872860) expected, got String(#21001240)
这似乎是合理的,因为我向 Student.create 方法发送了一个字符串而不是 State 对象。
在 RoR 中处理这个问题的最佳方法是什么?我正在手动获取控制器中的 State 对象并将其替换为参数哈希,但我认为应该是更好的方法。
非常感谢。 费尔南多
I have a very simple problem but cannot find a nice solution. I have a lookup code in ruby (for example, Students that live in a State):
# State lookup (id, name)
class State < ActiveRecord::Base
has_many :students
end
# Class that belogs to a state
class Student< ActiveRecord::Base
belongs_to :state
end
and in the view/students/new.html.erb view, I display the states as a drop down:
<p>
<%= f.label :state %><br />
<%= f.collection_select :state, State.find(:all),
:id, :name, :prompt => "Select a State" %>
</p>
so far, so good, but when I hit save I got an error:
State(#37872860) expected, got String(#21001240)
what seems reasonable, as I'm sending a string instead of a State object to the Student.create method.
Which is the best way of handling this in RoR? I'm getting the State object in the controller by hand and replacing it in the parameters hash, but I think should be a better way.
Thanks very much.
Fernando
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
:state_id
不是:state
:state_id
not:state
State.find(:all) 实际上应该是发生在你的控制器而不是你的视图中的事情。我什至认为不可能访问视图中的模型,这可能是您的问题。如果您在控制器中执行类似的操作:
@states = State.find(:all)
然后您在视图中使用 @states 变量:
"Select a State" %>
我希望有所帮助。
State.find(:all) should really be something that happens in your controller not your view. I don't even think its possible to access a model in the view, which may be your problem. If you do something like this in your controller:
@states = State.find(:all)
Then you use the @states variable in the view:
"Select a State" %>
I hope that helps.