开发者

problems with creating new item in nested resource

I have nested resources as follows:

employer.rb

class Employer < ActiveRecord::Base

    has_many :listings

end

listing.rb

class Listing < ActiveRecord::Base

    belongs_to :employer

end

I built both using basic scaffold generator.

Everything seems to work except when I create a new listing for employer. The route is

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

When I navigate to the new listing url (company/employer_id/listings/new)

开发者_Go百科

I get:

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

Here is the listings_controller code for #new

  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

Again, everything else works (show, edit, etc) -- I just can't get a new listing page to come up... Any help would be awesome.

Thanks!

//EDIT BELOW

  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

ERROR:

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>}


In the Employer model you have added the has_many :listings association. But in your controller you call @employer.Listing.new. The thing that does not match here is Listing and listings.

You should instead do it like this:

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

Sidenotes:

Don't forget to call save on the @listing, otherwise it will not get saved.

I prefer to use build instead of new, that way the listing is available in the Employer association directly. Both methods valid though depending on how you use them.


The employer has_many listings, so you have to call @employer.listings, with an s.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜