2013-11-17 2 views
0

Я новичок в rails и пытаюсь создать форму с простой формой, и у меня проблемы с ней, принимая контроллер, модель и представление. Я хотел использовать метод new_event, но сначала я хотел просто заставить его работать. Я действительно хочу отформатировать его намного лучше. Заранее спасибо. Здесь ошибка с трассировкой:Проблемы с simple_form_for и nomethoderror

NoMethodError in EventsController#new 

undefined method `[]' for nil:NilClass 
Rails.root: /home/saasbook/Documents/ronde 

Application Trace | Framework Trace | Full Trace 
    app/models/event.rb:36:in `validate' 
    app/models/event.rb:25:in `new_event' 
    app/controllers/events_controller.rb:20:in `new' 

Вот модель:

class Event < ActiveRecord::Base 

    # Associations 
    has_many :invitations 
    belongs_to :created_by, :class_name => 'User' 
    has_many :attending_users, :through => :invitations, :source => :user, :conditions => "status = 'confirmed'" 
    has_many :invited_users, :through => :invitations, :source => :invited_user, :conditions => "status = 'invited'" 

    validates_presence_of :description, :location, :name, :start, :created_by 
    attr_accessible :description, :end, :location, :name, :public, :start, :created_by, :event_type, :user_id 
    EVENT_OPTIONS = %w[food drink other] 
    after_initialize :init 

    def init 
    self.public ||= false 
    end 

    def new 
    self.create(:description, :end, :location, :name, :public, :start, :created_by, :event_type, :user_id) 
    end 

    def self.new_event(details, user) 
     @event = Event.new 
     @event.created_by = user 
     @flag = validate(details) 
     if @flag.empty? 
     @event.attributes = details 
     @event.save! 
     end 
     return @event, @flag 
    end 
    def self.validate(details) 
flag = {} 
flag['name'] = true if details[:name] == nil or details[:name] == "" 
flag['description'] = true if details[:description] == nil or details[:description] == "" 
flag['location'] = true if details[:location] == nil or details[:location] == "" 
flag['event_type'] = true if details[:event_type] == nil or details[:event_type] == "" 
return flag 

конец А вот мой контроллер и вид:

def new 

end 

def create 
    @event = Event.new 
    @event.created_by = current_user 
    @event.attributes = params[:event] 
    @event.save! 
    redirect_to user_dashboard_path 
end 

и

%body 
.container 
    %h2.title Create New Event 
    = simple_form_for(Event.new, :html => {:class => 'form-horizontal' }) do |form| 
     = f.hidden :created_by => current_user 
     = f.text_field :name,:placeholder => "What should we do?" 
     = f.text_area :description, rows: 3, :placeholder => "Give your friends some more details and convince them to come " 
     = f.text_field :location,:placeholder => "Where?" 
     = f.collection_select :event_type, Event::EVENT_OPTIONS, :to_s, :humanize, prompt: true 
     = f.datetime_select :start, :default => Time.now, :discard_month => true, :discard_year => true, :ampm => true, :minute_step =>15 
     = f.datetime_select :end, :default => Time.now, :discard_month => true, :discard_year => true, :ampm => true, :minute_step =>15 
     = f.submit value: 'create', class: 'btn btn-large btn-success' 
+0

Ваш код 'event.rb' кажется усеченным. Стек ссылается на метод 'validate' в строке 36, но вы даже не показываете, что много строк и нет' end' для 'class'. –

ответ

0

Почему вы определяете «новый» метод в вашей модели? Это один из этих священных слов рельсов, поэтому вы действительно не должны переопределять его, тем более, что похоже, что вы на самом деле ничего не делаете с ним. Кроме того, вы создаете «новый» метод экземпляра вместо метода класса, то есть вы не можете вызвать Event.new, а скорее Event.find (1) .new, что не будет работать, потому что тогда событие будет иметь уже созданы. Для получения дополнительной информации: http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

Так что, в основном, избавьтесь от своего «нового» метода экземпляра в модели. Тогда я бы изменил следующий код:

def create 
    @event = Event.new params[:event] # this grabs the params (and values) from the form 
    ## @event.created_by = current_user - don't need this because you have a hidden field for it 
    ## @event.attributes = params[:event] - unnecessary, you need to be defining your strong paramters below anyway if you're using rails 4 
    if @event.save! 
    redirect_to user_dashboard_path 
    else 
    #fail miserably 
end 
Смежные вопросы