我正在使用Rails 4.1.6
我正在尝试创建选择至少3项服务的能力,然后保存广告。
模型结构如下:
class Service < ActiveRecord::Base
belongs_to :advertisement
end
class Advertisement < ActiveRecord::Base
has_many :services
end
我的表格:
<% @services.each do |service| %>
<li>
<%= check_box_tag 'service_ids[]', service.id -%>
<%= h service.name -%>
</li>
<% end %>
控制器:
class AdvertisementsController < ApplicationController
before_action :authenticate_user!
before_action :set_advertisement, only: [:show, :edit, :update, :destroy]
respond_to :html, :xml, :json
def index
@advertisements = Advertisement.all
respond_with(@advertisements)
end
def show
@advertisement = Advertisement.find(params[:id])
respond_with(@advertisement)
end
def new
@advertisement = Advertisement.new
@services = Service.all
respond_with(@advertisement)
end
def edit
end
def create
@advertisement = Advertisement.new(advertisement_params)
if @advertisement.save
if params[:images]
params[:images].each { |image|
@advertisement.pictures.create(image: image)
}
respond_with(@advertisement)
end
else
format.html { render 'new'} ## Specify the format in which you are rendering "new" page
format.json { render json: @advertisement.errors } ## You might want to specify a json format as well
end
end
def update
@advertisement.update(advertisement_params)
respond_with(@advertisement)
end
def destroy
@advertisement.destroy
respond_with(@advertisement)
end
private
def set_advertisement
@advertisement = Advertisement.find(params[:id])
end
def advertisement_params
params.require(:advertisement).permit(:name, :user_id, :advertisement_id, :image,:terms_of_service,:region, :age, :height, :phone_number,:description)
end
end
当我检查multpile服务并单击“保存”时,没有错误。当我检查日志文件时,我收到了这条消息“
Parameters: ... "service_ids"=>["1", "2", "3"] ...
然后在控制台中我检查:
2.1.3 :008 >t = Advertisement.last (ALL OK)
....
2.1.3 :008 > t.services
=> #<ActiveRecord::Associations::CollectionProxy []>
这是错误的。关联中存在问题,但对我来说似乎没什么问题。
可能是什么问题? 感谢
答案 0 :(得分:1)
service_ids
中没有advertisement_params
。添加它们:
@advertisement = Advertisement.new(advertisement_params.merge(service_ids: params[:service_ids]))
# or
@advertisement = Advertisement.new(advertisement_params)
@advertisement.service_ids = service_ids