【发布时间】:2015-12-01 22:14:41
【问题描述】:
我是网络编程新手。所以我在网上搜索了一段时间自己解决了这个问题,但似乎没有人遇到类似的问题。
在我的程序中,我得到的用户输入包含一个新展位的管理员,该展位是通过我的 app/views/booths/new.html.erb 文件中的文本区域创建的,如下所示。
app/views/booths/new.html.erb:
<% provide(:title, 'Create New Booth') %>
<h1>Create New Booth</h1>
<% javascript_include_tag "booths" %>
<div>
<div>
<%= form_for(@booth) do |f| %>
<%= f.label :booth_name, "Name of the new Booth" %>
<%= f.text_field :booth_name %>
<%= f.label :booth_description, "Describe your new Booth" %>
<%= f.text_field :booth_description %>
<%= f.label :important_notice, "Any important notices?" %>
<%= f.text_field :important_notice %>
<span><br>Admins for this Booth?<br> </span>
<textarea id="create_booth_admins_textarea" rows="30" cols="50"> </textarea>
<%= f.submit "Create a new booth", :id => "booth_create_submit"%>
<% end %>
</div>
</div>
app/assets/javascripts/booths.js 摘录:
admins = $("textarea#create_booth_admins_textarea").val();
$('#booth_create_submit').click(function() {
$.ajax({
url: "/booths_create",
data: { "booth_admin_emails" : admins},
type: "post",
cache: false,
success: function () {
console.log("ajax successful");
alert("ajax successful");
},
error: fucntion() {
console.log("ajax error");
alert("ajax error")
}
});
});
app/controller/booths_controller.rb:
def new
@booth = Booth.new
@other_members = []
@booth_admins = []
end
def create
temp_hash = booth_params
@booth = Booth.new(temp_hash.except(:booth_admin_emails))
@booth.admin_id = current_user.id #fill in the Booth table
@booth_admins = temp_hash[:booth_admin_emails]
booth_admins = []
if @booth.save
#fill in join table
BoothUser.create(:user_id => current_user.id, :booth_id => @booth.id, :is_admin => true) #add current user
if !@booth_admins.nil?
booth_admins = @booth_admins.split(",")
end
if !booth_admins.empty?
booth_admins.each do |email|
BoothUser.create(:user_id => User.where("email=?", email).id, :booth_id => @booth.id, :is_admin => true)
end
end
# just a flash to tell user that new booth was created
name = @booth.booth_name
flash[:success] = "New Booth #{name} created!"
redirect_to '/booths'
else
render('show')
end
end
private
def booth_params
params.require(:booth).permit(:booth_name, :booth_description, :important_notice, :booth_admin_emails)
end
User和Booth属于has_many through关联,其中join表称为BoothUser,其中包含booth_id, user_id, is_admin的信息,其中id是特定用户和Booth在各自表中的索引, is_admin 是一个布尔值,用于检查用户是否是展台的管理员(具有编辑展台设置的权限)。
出现问题是因为在我的 Booth 表中,我只声明了展位的创建者,并且不跟踪该展位的给定管理员,但我试图通过查找连接表来找到该展位的这些管理员,其中booth_id 与该展位的索引匹配,is_admin 为真。
我一直试图将create_booth_admins_textarea 上的输入传递给控制器中的:booth_admin_emails,但到目前为止没有运气,因为没有任何东西传递到:booth_admin_emails。我猜这是因为:booth_admin_emails 不是Booth 或User 或BoothUser 模型的属性。
我在网上找到的是使用强参数(?)传递参数的方法,以允许使用 form_for 或 ajax 的模型属性。但似乎没有人将不是模型属性的输入传递给控制器。
所以,我想问有没有办法这样做,如果有,我该怎么做?还是只是不允许?
【问题讨论】:
标签: javascript ruby-on-rails ruby ajax ruby-on-rails-4.2