我有如下嵌套资源:
雇主.rb
class Employer < ActiveRecord::Base
has_many :listings
end
列表.rb
class Listing < ActiveRecord::Base
belongs_to :employer
end
我使用基本的脚手架生成器构建了两者。
除了我为雇主创建新列表时,一切似乎都正常。路线是
new_employer_listing GET
/company/:employer_id/listings/new(.:format)
{:action=>"new", :controller=>"listings"}
当我导航到新的列表 url (company/employer_id/listings/new)
我得到:
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>}
最佳答案
在 Employer 模型中,您添加了 has_many :listings
关联。但是在您的 Controller 中,您调用了 @employer.Listing.new
。这里不匹配的是Listing和listings。
你应该这样做:
@listing = @employer.listings.new(params[:listing)
旁注:
不要忘记在@listing 上调用save
,否则它不会被保存。
我更喜欢使用 build
而不是 new
,这样列表就可以直接在雇主协会中获得。这两种方法都有效,但取决于您如何使用它们。
关于ruby-on-rails - 在嵌套资源中创建新项目的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6784785/