我正在尝试在所有微博上实现高级搜索(通过关键字和目的-dropdown选项),但我甚至无法写入数据库搜索。我想我的问题可能是:模型构建,collection_select设置或控制器(大多数是到处都是)。 routes.rb具有所有资源,但是:搜索不是嵌套的
new.html.erb:
<%= form_for @search do |f| %>
<%= f.label :keywords %><br>
<%= f.text_field :keywords %>
<%= f.label :purpose_id %><
<%= f.collection_select :purpose_id, Micropost.order(:purpose), :id, :purpose_id, include_blank: true %>
<%= f.submit 'Buscar' %>
<% end %>
searches_controller.rb:
class SearchesController < ApplicationController
def new
@search = Search.new
end
def create
@search = Search.new(params[:search])
if @search.save
redirect_to @search
else
redirect_to root_url
end
end def show
@search = Search.find(params[:id])
end
private
def search_params
params.require(:search).permit(:keywords, :purpose_id)
end
schema.db:
create_table "microposts", force: :cascade do |t|
t.text "content"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "picture"
t.string "purpose"
t.index ["user_id", "created_at"], name: "index_microposts_on_user_id_and_created_at"
t.index ["user_id"], name: "index_microposts_on_user_id"
end
create_table "searches", force: :cascade do |t|
t.string "keywords"
t.integer "purpose_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
控制台出错:
通过SearchesController处理#创建为HTML参数:{&#34; utf8&#34; =&gt;&#34;✓&#34;,&#34; authenticity_token&#34; =&gt;&#34; wA3FRz .... 6Kg ==&#34;,&#34;搜索&#34; =&gt; {&#34;关键字&#34; =&gt;&#34;&#34;,&#34; purpose_id&# 34; =&gt;&#34; 18&#34;},&#34;提交&#34; =&gt;&#34; Buscar&#34;}
3ms完成500内部服务器错误(ActiveRecord:0.0ms)
ActiveModel :: ForbiddenAttributesError(ActiveModel :: ForbiddenAttributesError):
app / controllers / searching_controller.rb:8:在'create&#39;
中答案 0 :(得分:1)
您将原始param
直接传递到模型的构造函数中,而不是search_params
您需要/允许特定参数的位置。需要调用search_param
来做任何事情。
该行
@search = Search.new(params[:search])
需要
@search = Search.new(search_params)