在 Rails 上在模板 Ruby 中呈现 post 请求

Render post request in template Ruby on Rails

我一直在努力让表单 post 请求的内容呈现在 results.erb 模板上。 这是我的 宠物控制器:

class PetsController < ApplicationController

  # before_action :set_pet, only: [:show, :edit, :update, :destroy]
  PETFINDER = Petfinder::Client.new('xxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxx')
  # GET /pets
  # GET /pets.json
  def results
    @animal_list = Pet.all
  def search # new
    @pet = Pet.new
  end
  end


  def create
    Pet.destroy_all
     @pets = PETFINDER.find_pets(pet_finder_type, pet_finder_zip, count: 500)
     if params['pets']['breed'].empty?
      @selected_animals = @pets.select do |pet|
        pet.age == params['pets']['age']  &&
        pet.size == params['pets']['size'] &&
        pet.sex == params['pets']['sex']
      end
    else
      @selected_animals = @pets.select do |pet|
        pet.age == params['pets']['age']  &&
        pet.size == params['pets']['size'] &&
        pet.sex == params['pets']['sex'] &&
        pet.breeds.include?(params['pets']['breeds'])
      end
    end



      @selected_animals.each do |selected_animal|
        @desired_pet = Pet.create(name: selected_animal.name)
        @desired_pet.age = selected_animal.age
        @desired_pet.size = selected_animal.size
        @desired_pet.sex = selected_animal.sex
        @desired_pet.breed = selected_animal.breeds
        # @desired_pet.picture = selected_animal.photos.first.medium
        @desired_pet.description = selected_animal.description
        @desired_pet.shelter_id = selected_animal.shelter_id
        @desired_pet.last_update = selected_animal.last_update
        @desired_pet.save
      end
    # binding.pry
  end
  private
    # Never trust parameters from the scary internet, only allow the white list through.
    def pet_finder_type
      params[:pets][:type]

    end

    def pet_finder_zip
      params[:pets][:zip]

    end
end

routes.rb

root 'welcome#index'

  get '/pets' => 'pets#search'

  post '/pets' => 'pets#create'

  get '/pets' => 'pets#results'

我希望能够调用我所有的 Pet 实例并在 pets/results.erb 中渲染它们,对其进行迭代并获取其值。 像这样:

pets/results.erb

<% @animal_pet.each do |pet| %>
<ul>
<li><%= pet.age %></li>
</ul>
<%end%>

我在 search.erb 中提交表单后得到 Missing template pets/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "/Users/cyrusghazanfar/Desktop/Purrfect-Match/app/views" 谁能帮我在这里设置一个正确的路线和方法。

Rails 将视图模板与您的每个控制器操作相关联。虽然 'create' 操作通常不与创建视图配对,但 Rails 将尝试将操作的输出重定向到 create.html.erb 模板,除非另有说明。例如:

def create @pets = PETFINDER.find_pets(pet_finder_type, pet_finder_zip, count: 500) ... redirect_to action: 'results' end

将输出重定向到当前控制器的results动作。这一切都在这里涵盖:http://guides.rubyonrails.org/layouts_and_rendering.html