Rails 将表单提交链接到对象
在 Rails 项目中,我有两个实体,用户和机构,它们具有多对多关系。
他们的视图是为了创建新用户和机构而设置的,但我想要另一个视图来链接这两者。
在rails控制台中,我所要做的就是
myuser.institutions << the_institution_i_just_created
控制器可以完成一些工作,但是我如何处理提交和表单?我想使用一个选择框,以便输入仅限于已经存在的机构。
<select id="institution_selection" name="institution_sel">
<% selections = []
Institution.all.each do |institution|
pair = [institution.name, institution.id]
selections.concat([pair])
end
%>
<%= options_for_select(selections) %>
</select>
因此,总而言之,问题是如何将此提交映射到对象,以便在控制器中我可以将其添加到关系中?
解决方案是:
好吧,这就是我想出的解决方案,我确信有更好的方法来解决它,我会继续研究它,但至少我得到了接近我目标的东西为了
def test
if !session[:user]
redirect_to users_path, notice: "Please login first"
end
if params[:institution]
@user = User.find(session[:user])
@institution = Institution.find(params[:institution][:id])
@user.institutions << @institution
redirect_to @user, notice: "Institution was successfully added "
end
end
和为了视图
<%= form_tag("/users/test", :method => "post") do %>
<%= collection_select :institution, :id, Institution.all, :id, :name %>
<%= submit_tag("Search") %>
<% end %>
In a rails project I have two entities, Users and Institutions, they have a many-to-many relationship.
The views for them are set up to create new users and institutions but I want to have another view for linking the two.
In rails console all I have to do is
myuser.institutions << the_institution_i_just_created
The controller can do some of the work but how do I handle the submissions and the forms? I want to use a selection box so that the input is limited to the Institutions already in existence.
<select id="institution_selection" name="institution_sel">
<% selections = []
Institution.all.each do |institution|
pair = [institution.name, institution.id]
selections.concat([pair])
end
%>
<%= options_for_select(selections) %>
</select>
So the question in summary is how do I map this submission to an object so that in the controller I can do add it to the relation?
The solution was:
Alright, so this is the solution I came up with, I'm sure there is a better way to go about it and I'll continue to look into it but at least I got something close to what I was aiming for
def test
if !session[:user]
redirect_to users_path, notice: "Please login first"
end
if params[:institution]
@user = User.find(session[:user])
@institution = Institution.find(params[:institution][:id])
@user.institutions << @institution
redirect_to @user, notice: "Institution was successfully added "
end
end
and for the view
<%= form_tag("/users/test", :method => "post") do %>
<%= collection_select :institution, :id, Institution.all, :id, :name %>
<%= submit_tag("Search") %>
<% end %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
collection_select
Use
collection_select