我正在尝试使用虚假活动记录(在db中没有持久性的模型)。
我按照这个例子: https://quickleft.com/blog/using-faux-activerecord-models-in-rails-3/
我有这个错误:
SearchController中的ArgumentError #new 错误的参数数量(2对1)
app / models / search.rb:32:in assign_attributes'
app/models/search.rb:27:in
初始化'
app / controllers / search_controller.rb:4:new'
app/controllers/search_controller.rb:4:in
新'
看来,当你调用Search.new时,它需要参数,但我的目标是使它成为一个空的搜索对象。
这是我的模型,控制器,视图,路线:
模型
class Search
include ActiveModel::MassAssignmentSecurity
TRUE_VALUES = ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES
attr_accessor :query
attr_reader :safe_search, :results_per_page
alias_method :safe_search?, :safe_search
attr_accessible :query, :safe_search, :results_per_page
RESULTS_PER_PAGE = [10, 25, 50, 100].freeze
include ActiveModel::Conversion
include ActiveModel::Validations
validates :query, presence: true
validates :results_per_page, presence: true, inclusion: { in: RESULTS_PER_PAGE }
def persisted?
false
end
def initialize(attributes = {})
assign_attributes(attributes)
yield(self) if block_given?
end
def assign_attributes(values, options = {})
sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
send("#{k}=", v)
end
end
def results_per_page=(value)
@results_per_page = value.to_i
end
def safe_search=(value)
@safe_search = TRUE_VALUES.include?(value)
end
end
控制器
class SearchController < ApplicationController
def new
@search = Search.new
render "search/new.html.erb"
end
def create
@search = Search.new(params[:search])
# TODO: use the @search object to perform a search. Adding
# a `results` method on the search object might be a good starting point.
end
end
查看:search / new.html.erb
<%= form_for @search do |f| %>
<%= f.label :query %>
<%= f.text_field :query %>
<%= f.label :safe_search %>
<%= f.check_box :safe_search %>
<%= f.label :results_per_page %>
<%= f.select_box :results_per_page %>
<%= end %>
答案 0 :(得分:0)
以下是我找到的解决方案: 在我使用的模型中:
def initialize(attributes = {})
assign_attributes(attributes)
end
def assign_attributes(attributes)
sanitize_for_mass_assignment(attributes).each do |k, v|
send("#{k}=", v)
end
end
以下是我在控制器中的new和create方法:
def new
@search = Search.new
render "search/new.html.erb"
end
def create
@search = Search.new(params[:search])
respond_to do |format|
format.html { render :template => "search/create.html.erb" }
end
end
顺便说一下,我必须将我的控制器重命名为SearchesController,因为控制器必须是多元化的。
这是我的new.html.erb视图:
<%= form_for @search, url: { action: "create" }, :method => :post do |f| %>
<%= f.label :query %>
<%= f.text_field :query %>
<%= f.label :safe_search %>
<%= f.check_box :safe_search %>
<%= f.label :results_per_page %>
<%= f.select(:results_per_page, [10, 25, 50, 100]) %>
<%= f.submit %>
<% end %>
我希望这对某些人有用。