假设我在作者下创作一本书,所以我必须选择一位现有作者或创作一本。好吧,我以为我可以有一个搜索领域;通过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 %>
...
它太奇怪而复杂了吗?我想不出任何其他方式来搜索/查找或填写表格。