我正在开发一个应用程序,用户可以在该应用程序中通过我的应用程序在Amazon(借助Vacuum)中搜索图书,然后将图书数据记录到他们的图书馆中。

当您搜索书籍时,它会遍历所有结果并将其放入缩略图中。每个缩略图中都有一个按钮,用于打开带有隐藏标签表单的模式。当用户单击提交按钮时,该书的标题将保存到新书中。唯一的问题是标题被保存为{:value=>"the title of the book that was saved"}

这是new.html.erb中具有搜索框的部分:

<%= form_tag({controller: "books", action: "new"}, method: "get", id: "search-form") do %>
          <%= text_field_tag :keywords, params[:keywords], placeholder: "Search for a book", class: "form-control" %>
        <% end %>


这是new.html.erb的一部分,具有隐藏的形式:

<% @results.each do |result| %>
  …
<%= form_for @book do |f|%>
                        <%= hidden_field_tag :title, class: 'form-control', value: result.name %>

                    <%= f.submit "Add book", class: "btn btn-default green-hover" %>

                <% end %>
    …
    <% end %>


这是控制器中的new和create动作:

def new
    @book = current_user.books.build if logged_in?

    # Search actions
    if params[:keywords]
        request = Vacuum.new

    request.configure(
      aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
      aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
      associate_tag: 'my associate tag is here'
    )
    keywords = params[:keywords]
    params = {
      'SearchIndex' => 'Books',
      'Keywords'=> keywords,
      'ResponseGroup' => "ItemAttributes,Images"
    }

    raw_results = request.item_search(query: params)
    hashed_results = raw_results.to_h

    @results = []

    hashed_results['ItemSearchResponse']['Items']['Item'].each do |item|
      result = OpenStruct.new
      result.title = item['ItemAttributes']['Title']
      result.url = item['DetailPageURL']
      result.image_url = item['MediumImage']['URL']
      result.author = item['ItemAttributes']['Author']
      result.pages = item['ItemAttributes']['NumberOfPages']
      @results << result
    end
  end
end

def create
    @book = @list.books.build(book_params)
    if @book.save
        flash[:success] = @book.title + "was added to your log."
        redirect_to list_path(@book.list_id)
    else
        render 'books/new'
    end
end


我尝试在book.rb中使用gsub对其进行修复,但这仅更改了Flash消息中的文本,并且仍保存为{:value=>"the title of the book that was saved"}

after_create :init

private
def init
  puts "Init was called!"
  self.title.gsub!('{:value=>"', " ")
  self.title.gsub!('"}', " ")
end


我该如何更改它,以免它不包含带有{:value=>}的标题?

最佳答案

我认为隐藏字段标记不正确。

<%= hidden_field_tag :title, class: 'form-control', value: result.name %>


尝试

<%= hidden_field_tag :title, result.name %>

09-10 16:05