rails 4.0 undefined method -
i have opportunity
model has activity
nested resource. on opportunities/show
page, have list of activities opportunity , form add new activities. when click "add activity" get:
undefined method `activities' nil:nilclass
here error source:
# post /activities.json def create @activity = @opportunity.activities.new(activity_params) if @activity.save redirect_to @opportunity, notice: 'activity has been added' else
i defined opportunity
model having many activities
, activities belongs to
opportunity. here relevant parts of activity
controller:
def create @activity = @opportunity.activities.new(activity_params) if @activity.save redirect_to @opportunity, notice: 'activity has been added' else redirect_to @opportunity, alert: 'unable add activty' end end
and here views/activities/new code
<%= form_for ([@opportunity, @opportunity.activities.new]) |f| %> <div class="field"> <%= f.label "date assigned" %> <br /> <%= f.text_field :date_assigned %> </div> <div class="field"> <%= f.label "date due" %> <br /> <%= f.text_field :date_due %> </div> <div class="field"> <%= f.label "description" %> <br /> <%= f.text_field :description %> </div> <div class="field"> <%= f.label "status" %> <br /> <%= f.text_field :status %> </div> <div class="actions"> <%= f.submit 'add' %> </div> <% end %>
my routes:
resources :opportunities resources :activities end
thank you!!
your @opportunity
undefined(nil) in block.
you must @opportunity
prior building activities on :
@opportunity = opportunity.find(params[:opportunity_id])
(reason :opportunity_id
: since activitycontroller
, model nested, conventional nested restful resources (as specified in routes), parameter automatically assigned model_id => opportunity_id
)
changed code:
def create @opportunity = opportunity.find(params[:opportunity_id]) @activity = @opportunity.activities.new(activity_params) if @activity.save redirect_to @opportunity, notice: 'activity has been added' else
also, recommend use build
instead of new
while building object relations.
Comments
Post a Comment