2011-07-22 64 views
1

創建新的項目我有嵌套資源如下:問題在嵌套的資源

employer.rb

class Employer < ActiveRecord::Base 

    has_many :listings 

end 

listing.rb

class Listing < ActiveRecord::Base 

    belongs_to :employer 

end 

我都建成使用基本腳手架發電機。

除了當我爲僱主創建新的列表時,一切似乎都有效。這條路線是

new_employer_listing GET 
/company/:employer_id/listings/new(.:format) 
{:action=>"new", :controller=>"listings"} 

當我瀏覽到新上市的URL(公司/ employer_id /上市/新)

我得到:

NoMethodError in ListingsController#new 
undefined method `listing' for #<Employer:0x102dd5e48> 

這裏是#NEW

的listings_controller碼
def new 
    @employer = Employer.find_by_username(params[:employer_id]) 
    @listing = @employer.listing.new 

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

再次,其他一切工作(顯示,編輯等) - 我只是不能得到一個新的上市頁面上來.. 。 任何幫助都是極好的。

謝謝!

//編輯下面

def create 
    @employer = Employer.find_by_username(params[:employer_id]) 
    @listing = @employer.listings.new(params[:listing]) 

    respond_to do |format| 
     if @listing.save 
     format.html { redirect_to(@listing, :notice => 'Listing was successfully created.') } 
     format.xml { render :xml => @listing, :status => :created, :location => @listing } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @listing.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

錯誤:

No route matches {:action=>"show", :controller=>"listings", :id=>#<Listing id: 20, job_title: "asd", location: nil, status: nil, industry: nil, years: nil, degree_type: nil, degree_field: nil, employer_id: 1, employers_id: nil, user_id: nil>}

回答

2

在僱主模型中,您添加了has_many :listings關聯。但是在您的控制器中,您可以撥打@employer.Listing.new。這裏不匹配的是列表和列表。

你應該做的,而不是像這樣:

@listing = @employer.listings.new(params[:listing) 

圖片的標題說明:

不要忘記呼籲@listing save,否則將無法得到保存。

我傾向於使用build而不是new,這樣該列表可直接在僱主協會中使用。兩種方法都有效,但取決於你如何使用它們。

+0

嗯謝謝 - 我「geting'沒有路由匹配{:controller =>」列表「}} - 任何其他建議?再次感謝! – stewart715

+0

瞭解它 - 謝謝!它是一個窗體語法錯誤:x – stewart715

+0

快速問題,如果你有時間:我用我的創建定義來編輯帖子,創建完成後重定向,但出現錯誤(上面也顯示)。感謝您幫助newb:D – stewart715

1

僱主has_many上市,所以你必須調用@employer.listings,以S。

+0

是這樣的? '@listing = @ employer.listings.new'當我這樣做時,我得到:'沒有路由匹配{:controller =>「列表」}'這很有趣,因爲有一個列表控制器......奇怪的是其他所有工作。 – stewart715