Rails:如何接收非模型表单输入,将其转换为模型属性,然后保存该模型
背景:
- 我有一个 form_for 映射到一个名为 List 的模型。
- 列表具有属性:name、id、receiver_id、assigner_id。
- 我希望用户(或列表分配者)能够选择列表接收者。
- 我希望分配者输入电子邮件,而不是接收者的 ID。
问题:
- 我不确定如何使用表单接收电子邮件地址,使用该电子邮件地址运行“User.find_by_email(xx).id”查询,然后将返回的 id 分配给列表的receiver_id 属性。
当前代码:
lists_conroller.rb
class ListsController < ApplicationController
before_filter :current_user
def new
@list = List.new
end
def create
@list = List.new(params[:list])
@list.assigner = @current_user
#@list.receiver = User.find_by_id(:receiver_id)
@list.save
redirect_to @list
end
def show
@list = List.find(params[:id])
end
def update
@list = List.find(params[:id])
end
end
列表\new.html.erb
<%= form_for @list do |f| %>
<%= f.label :name, 'Name'%>
<%= f.text_field :name %>
<%= f.label :receiver_id, 'Receiver ID'%>
**I want this to be the e-mail input, rather than the integer id.**
<%= f.text_field :receiver_id %><br />
<%= f.submit :submit %>
<% end %>
Background:
- I have a form_for mapped to a model called List.
- List has attributes: name, id, receiver_id, assigner_id.
- I want the user( or list assigner) to be able to choose a list receiver.
- I want the assigner to input an e-mail, rather than the receiver's id.
Problem:
- I am not sure how to use a form to receive an e-mail address, run a "User.find_by_email(xx).id" query using that e-mail address, and then assign the returned id to the List's receiver_id attribute.
Current Code:
lists_conroller.rb
class ListsController < ApplicationController
before_filter :current_user
def new
@list = List.new
end
def create
@list = List.new(params[:list])
@list.assigner = @current_user
#@list.receiver = User.find_by_id(:receiver_id)
@list.save
redirect_to @list
end
def show
@list = List.find(params[:id])
end
def update
@list = List.find(params[:id])
end
end
lists\new.html.erb
<%= form_for @list do |f| %>
<%= f.label :name, 'Name'%>
<%= f.text_field :name %>
<%= f.label :receiver_id, 'Receiver ID'%>
**I want this to be the e-mail input, rather than the integer id.**
<%= f.text_field :receiver_id %><br />
<%= f.submit :submit %>
<% end %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用户创建新列表,他作为分配者。在这个创造过程中也必须有一个接收者。我做对了吗?
我认为应该从可能的接收者列表中选择接收者(也许是一个选择框?这将取决于可能的接收者的数量,但不想在其中列出 1000 多个用户 - 如果有很多用户,你可以这样做当用户输入几个字母时进行 ajax 搜索)
分配者然后选择一个用户(使用相应的 id 作为值),一切都应该没问题。
User creates new list, with him as the assigner. In that creation process there must be a receiver too. Did I get this right?
I think the receiver should be selected from a list of possible receivers (maybe a select box? this will depend on the number of possible receivers though, wouldn't want to list 1000+ users in there - if there are many users you could do an ajax search when the user types a few letters)
The assigner then selects a user (with the corresponding
id
as the value) and everything should be ok.我的问题的答案是“虚拟属性......”
The answer to my question is "Virtual Attributes..."