我正在创建一个允许人们发布广告的网站。在创建新广告时,我希望他们从我的种子中预先填充的列表中为该广告选择一个类别。rb。因此,我建立了以下模型和关联。
应用程序/型号/广告rb
class Ad < ApplicationRecord
# validations
belongs_to :category
end
应用程序/型号/类别。rb型
class Category < ApplicationRecord
has_ancestry
extend FriendlyId
friendly_id :name, use: :slugged
has_many :ads
end
然后我修改了我的广告表单,使用简单表单
f.association :category
从预先填充的类别列表中生成选择(见下文)
应用程序/视图/广告/新建。html。雇员再培训局
<%= simple_form_for @ad, url: ads_path do |f| %>
<%= f.input :title, label: false, placeholder: "Item/Service for Sale" %>
<%= f.association :category, label_method: :name, value_method: :id %>
# other stuff
<% end %>
我继续得到以下错误:“Ads中的NoMethodError#new:未定义的方法'category\u id'for”#
你是说?类别
类别=”
知道问题出在哪里吗?此外,以下是我的Ads控制器中的新建和创建操作:
class AdsController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
def new
@ad = Ad.new
end
def create
@ad = current_user.ads.create(ad_params)
if @ad.valid?
flash[:notice] = "Ad created successfully"
redirect_to ad_path(@ad)
else
render :new, status: :unprocessable_entity
end
end
# other actions
private
def ad_params
params.require(:ad).permit(:title, :cost, :description, :quantity, :phone, :email, :accepted)
end
end
如果您能帮助我们完成此表格,我们将不胜感激!