我是Nested Forms的新手。我正在构建一个表单,公司可以在几个类别下创建Promos。我继续为Class获取未定义的方法“model_id”。我的代码和确切的错误消息如下: -
错误讯息: -
undefined method `category_id' for #<Company:0x007fd43828b6f8>
<%= f.collection_select :category_id, Category.all, :id, :name, {include_blank: 'Choose Category'}, required: true %>
<%= render partial: 'promo', locals: {f: f}%>
模特: -
class Company < ActiveRecord::Base
has_many :users, :through => :company_customers
has_many :company_users
has_many :categories, :through => :category_companies
has_many :category_companies
accepts_nested_attributes_for :category_companies
accepts_nested_attributes_for :categories s
end
class CompanyCategory < ActiveRecord::Base
belongs_to :company
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :company_categories
has_many :companies, :through => :company_categories
has_many :promos
accepts_nested_attributes_for :company_categories
end
class Promo < ActiveRecord::Base
belongs_to :category
end
控制器: -
class CompaniesController < ApplicationController
def new
@company = Company.new
end
def create
@company = Company.new(company_params)
respond_to do |format|
if @company.save
format.html { redirect_to @company, notice: 'Company was successfully created.' }
format.json { render :show, status: :created, location: @company }
else
format.html { render :new }
format.json { render json: @company.errors, status: :unprocessable_entity }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_company
@company = Company.find(params[:id])
end
def company_params
params.require(:company).permit(:company_name, :registration_no, :address, :phone_no, :outlet_location, company_categories_attributes: [:id, :company_id, :category_id, category_attributes:[:id, :name, promo_attribute:[:id, :name, :description]]])
end
end
查看: -
<%= form_for(:company) do |f| %>
<div class="medium-6 columns">
<%= f.collection_select :category_id, Category.all, :id, :name, {include_blank: 'Choose Category'}, required: true %>
<%= render partial: 'promo', locals: {f: f}%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
_promo.html.erb
<%= f.fields_for :promos do |promo| %>
<h4 class="text-center">Promotions to be offered</h4><br>
<div class="row">
<div class="medium-6 columns">
<%= f.text_field :name, placeholder: "Name", required: true %>
</div>
<div class="medium-6 columns">
<%= f.text_field :description, placeholder: "Description", required: true %>
</div>
</div>
<% end %>
<p><%= f.link_to_add "Add More Promos", :promos %> </p>
感谢帮助。非常感谢!
答案 0 :(得分:0)
从docs开始,collection_select具有以下用途:
collection_select(object,method,collection,value_method,text_method,options = {},html_options = {})
他们有这个例子:
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
将使用这样的:
f.collection_select :category_id, Category.all, :id, :name, {include_blank: 'Choose Category'}, required: true
所以,当你这样做时:
object
我想也许你错过了:post
论点?比如,他们有0
。