开发者

Rails : Issue with nested resources : new form

开发者 https://www.devze.com 2023-02-26 18:12 出处:网络
I have two models . Events and Questions. Event has many questions. I am trying to create a new Question from the Events#show view .

I have two models . Events and Questions. Event has many questions. I am trying to create a new Question from the Events#show view . The link comes out to be something like /events/:event_id/questions/new . But when clicked it gives errors -

undefined method `model_name' for NilClass:Class

I guess there is error either with my _form.html or the new method in Questions controller.

Can someone please help ?

Event.rb

class Event < ActiveRecord::Base

  has_many :questions

end

Question.rb

class Question < ActiveRecord::Base
   belongs_to :event

end

Routes.rb

resources :events do

    resources :questions 

end

Events - show.html.erb

<p> <%= link_to开发者_如何学编程 "Ask", new_event_question_path(@event) %> </p>

Question Controller

before_filter(:get_event)

  private
def get_event
    @event = Event.find(params[:event_id])
end

 def new
    @question = Question.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @question }
    end
  end

_form.html.erb

<%= form_for([@event,@question]) do |f| %>
  <% if @question.errors.any? %>
    <div id="error_explanation">

........
........
......
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>


you you have declared private in the beginning of the questions controller all that comes after that is also made private and your action new is also declared private cut it and paste it before the private and then try


Read through these resources:

  1. http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

  2. http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

  3. http://railscasts.com/episodes/196-nested-model-form-part-1

This should help you set-up your models and get working.

0

精彩评论

暂无评论...
验证码 换一张
取 消