mercredi 25 mars 2015

Creating new nested model in RoR

i am pretty new in RoR and trying to understand the basics. I have two models



class Beekeeper < ActiveRecord::Base
has_many :apiaries, dependent: :destroy
end


and



class Apiary < ActiveRecord::Base
belongs_to :beekeeper
end


The controller for the Beekeepers is working just fine, but i have trouble routing to the 'new' route for apiary creation.


The apiaries controller is



class ApiariesController < ApplicationController

def new
@beekeeper = Beekeeper.find(params[:beekeeper_id] )
@apiary = @beekeeper.apiaries.build
respond_to do |format|
format.html { render new }
end
end


private

def apiary_params
params.require(:apiary).permit(:name, :location, :numberofbeehives, :beekeeper_id)
end
end


Also in beekeepers controller we have a



def current_beekeeper
@current_beekeeper ||= Beekeeper.find_by(id: session[:beekeeper_id])
end


I am using 'application.html.erb' for rendering a header and a footer in all pages. The first problem is in the '_header.html.erb':



<% if logged_in? %>
<li><%= link_to "Insert Apiary", new_beekeeper_apiary_path(@beekeeper) %></li>
<li><%= link_to "All Beekeepers", beekeepers_path %></li>

<li><%= link_to "Profile", beekeeper_path(@beekeeper) %></li>
<li><%= link_to "Settings", '#' %></li>
<li>
<%= link_to "Log out", logout_path, method: "delete" %>
</li>
</ul>


If in the links for 'profile' and 'new_apiary' i include (@beekeeper) i get a: $No route matches {:action=>"new", :beekeeper_id=>nil, :controller=>"apiaries"} missing required keys: [:beekeeper_id]$


If in the above links i include instead of $@beekeeper$ -> $current_beekeeper$ (or just current_beekeeper dunno why) the pages load just fine but then when i click on the new apiary link i get either (Couldn't find Beekeeper with 'id'=) if i use $ @beekeeper = Beekeeper.find(params[:id] ) in my apiaries controller or a stack too deep error (it is recursing around lines 4 and 5 of the controller) if i use $ @beekeeper = Beekeeper.find(params[:beekeeper_id] )$ which i think should work.


Forgot to mention my routes files is



Rails.application.routes.draw do

resources :beekeepers do
resources :apiaries
end
end


and i do have a beekeeper_id field in my apiaries db. Thanks for any help !


Aucun commentaire:

Enregistrer un commentaire