I am trying to use faux active record (a model that has no persistence in db).
I followed this example: http://ift.tt/1JuLUKx
And I have this error:
ArgumentError in SearchController#new wrong number of arguments (2 for 1)
app/models/search.rb:32:in assign_attributes' app/models/search.rb:27:in
initialize' app/controllers/search_controller.rb:4:in new' app/controllers/search_controller.rb:4:in
new'
It seems that when you call Search.new it needs the parametters but my goal is to make it an empty Search object.
Here are my model, controller, view, route:
Model
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
Controller
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
View: 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 %>
Aucun commentaire:
Enregistrer un commentaire