仅在单击Rails中的“提交”按钮后,才如何启动每个循环?

时间:2019-01-26 13:33:56

标签: ruby-on-rails ruby rest

我有一个Rails应用程序,可以搜索数据库并返回项目。目前,在我看来,它会自动返回默认搜索结果(“”),而无需点击我的Submit_tag。一旦点击了commit_tag,我该如何做才能使该动作发生?任何帮助将不胜感激!

这是我的观点:

 <%= form_tag(new_design_path, method: :get) do %>
    <%= label_tag(:q, "Search all designs:") %>
    <%= text_field_tag(:q) %>
    <%= submit_tag("Search") %>
  <% end %><br>
  <!-- Button to return one random design --> 
  <%= form_tag(new_design_path, method: :get) do %>
    <%= label_tag(:q, "Inspire me! Click here for a random design:") %>
    <%= submit_tag("Random Design") %>
  <% end %>

  <h2>Search results:</h2>

  <% @random.each do |design| %>  
    <h3><%= design['name'] %></h3>
    <h5><%= image_tag design['thumbnail_url'] %></h5>
  <% end %>

  <% @search.each do |design| %>  
  <div class="design">
    <h3 class="design_name"><%= design['name'] %></h3>
    <h5><%= image_tag design['thumbnail_url'] %></h5>
    <%= button_to 'Save to Favourites',
      designs_path(
        design: design.slice('name', 'thumbnail_url') 
      ),method: :post %>
    </div>
  <% end %>

还有我的控制器:

class DesignsController < ApplicationController
    def index
        @designs = Design.all.order("created_at DESC")
    end

    def new
        # returns an array of hashes
        @search = SpoonflowerApi.new.find(params[:q])['results']
        @random = SpoonflowerApi.new.random(rand(1..740579), 1)['results']
    end

    def create
    @design = Design.new(design_params)
    @design.save
        if @design.save
            flash[:notice] = 'Design has been added to favourites!'
        else
            flash[:notice] = 'Design already in Favourites!'
    end
    redirect_to new_design_path
  end

  def destroy
    @design = Design.find(params[:id])
    @design.destroy
    flash[:notice] = 'Design removed from favourites!'
    redirect_to designs_path
  end

  private

  def design_params
    params.require(:design).permit(:name, :thumbnail_url) 
  end
end

2 个答案:

答案 0 :(得分:1)

new用于填充初始格式,因此,如果您不需要这些字段的任何内容,则只需将@search@random都设置为一个新的空数组。您没有为模型显示任何代码,因此还不清楚Api是什么。

提交表单后,应调用

show

def new
  @search = []
  @random = []
end

然后将提供搜索结果或随机记录的逻辑移到show方法中

def show
  # not sure what you want to do here
  # since it seems like you have 2 buttons you need logic to provide data 
  # based on the button 
  # maybe something like this
  if params[:q].nil?
    @search = []
    @random = Api.new.random(rand(1..740579), 1)['results']
  else
    @search = Api.new.find(params[:q])['results']
    @random = []
  end
end

答案 1 :(得分:0)

如果我对您的理解正确,那么在单击搜索按钮之前,您的视图会显示一些搜索结果。

由于您直接将params [:q]发送到SpoonflowerApi,所以我猜它会返回一些默认值,然后您的视图会绘制它。

只需将您的控制器更新为:

def new
    @search=[]

    @search = SpoonflowerApi.new.find(params[:q])['results'] unless params[:q].nil?
    @random = SpoonflowerApi.new.random(rand(1..740579), 1)['results']
end