我有一个使用HTTParty gem的外部设计搜索api的Rails api。使用返回到我的视图的数据,我希望能够将所选条目保存到数据库中。有点像书签功能。无论如何,在每个搜索结果项旁边都有一个按钮可以实现此目的?任何帮助将不胜感激。我当前的代码如下。
设计控制器:
class DesignsController < ApplicationController
def index
@search = Api.new.find(params[:q])['results']
end
end
Class方法:
class Api
include HTTParty
base_uri "http://search.example.com/searchv2"
attr_accessor :name, :limit, :offset
# Find a particular design, based on its name
def find(name)
self.class.get("/designs", query: { q: name }).parsed_response
end
end
查看:
<h1>Design Search</h1>
<%= form_tag(designs_path, method: :get) do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
<h2>Search results:</h2>
<% @search.each do |design| %>
<h3><%= design['name'] %></h3>
<h5><%= image_tag design['thumbnail_url'] %></h5>
<% end %>
设计模型:
class Design < ApplicationRecord
end
答案 0 :(得分:0)
app / views / designs / index.html.erb:
...
<% @search.each do |design| %>
<h3><%= design['name'] %></h3>
<h5><%= image_tag design['thumbnail_url'] %></h5>
<%= button_to 'Save',
designs_path(
design: design.slice('name', 'thumbnail_url') # etc...
),
method: :post,
data: { disable_with: 'Loading...' }
%>
<% end %>
app / config / routes.rb:
resources :designs, only: [:index, :create]
app / controllers / designs_controller.rb:
class DesignsController < ApplicationController
# ...
def create
@design = Design.new(design_params)
@design.save!
# just an example...
redirect_to designs_path, success: 'Design has been saved!'
end
private
def design_params
params.require(:design).permit(:name, :thumbnail_url) # etc...
end
end
Design
模型需要具有您要保存的属性(即:name
和:thumbnail_url
?)。我的假设是您已经创建/迁移了这些属性。如果还没有,那么请添加它们。<button>
的{{1}}(即,他们可以在保存设计时按自己的意愿修改设计的“名称” ),那么我的上述解决方案仍然不是最佳解决方案,尽管为了简单起见,并假设此漏洞对您来说不是问题,那么上面的代码已经足够了。