假设我正在根据作者创建一本书,因此我必须选择现有作者或创建一个。好吧,我以为我可以有一个搜索字段;通过 CoffeeScript,我将$.ajax()
返回一个视图,其中包含一个带有结果的表格和一个用于选择项目的按钮。如果没有记录,会有作者表单部分的链接。不过,我不确定这是最好的方法。
问题是我无法将f
变量传递给返回视图,以防用户需要填写表单。我尝试将表单的链接保留在原始视图中,但我不知道何时通过 JS 触发它。
这就是我现在所拥有的:
# new.html.erb
<%= simple_form_for @author do |f| %>
<%= render 'search', f: f %>
...
<% end %>
# _search.html.erb
<%= text_field :author_search_name %>
<%= link_to 'Search', '#', id: 'author_search_submit',
ajax_path: author_search_path %>
<div id="author_search_result"></div>
# author.js.coffee
$('#author_search_result').hide
$('#author_search_submit').click (event) ->
$.ajax
url: $(this).attr('ajax_path'),
params: { chassi: $('#author_search_name').val() },
success: (data) ->
$('#author_search_result').html(data).show
还有几个文件,但这些是最重要的。这author_search_path
是带有结果记录的视图或必须填写表格的警告。我真的很困惑,因为我已经解决这个问题好几天了,但似乎没有任何效果。我希望这足以解释我的问题。
更新:
# author_search.html.erb
<% if @authors.size > 0 %>
<table>
...
<% @authors.each do |author| %>
<tr>
...
<td><%= link_to "Select", '#', data_author_id: author.id %></td>
</tr>
<% end %>
</table>
<% else %>
<p>There are no authors with this name.
You can create a new one by <%= link_to_add_fields 'clicking here', f %></p>
<% end %>
在上面的代码中,我无法访问该f
变量,这不能让我呈现表单。
# application_helper.rb
def link_to_add_fields(name, f)
link_to name, '#', data: { fields: render('fields', f: f).gsub("\n", "") }
end
# _fields.html.erb
<%= f.input :name %>
<%= f.input :age %>
...
是不是太奇怪太复杂了?我想不出任何其他方式来搜索/查找或填写表格。