【发布时间】:2015-08-16 23:50:48
【问题描述】:
我有一个带有select_tag 和options_from_collection_for_select 的表单,我似乎无法通过。在视图中,当上传 id 设置为 uploadzip_id 时,我得到一个 302 重定向,当它设置为 uploadzip_ids 时,我得到一个 Unknown Attribute 错误。
我有点困惑,因为我的关系与外键一起设置。我确实有另一个带有复选框的模型,称为Uploadpdf,它工作正常。
这里是设置..
class Campaign < ActiveRecord::Base
has_one :uploadzip
end
class Uploadzip < ActiveRecord::Base
belongs_to :campaign
end
db/schema.rb
create_table "campaigns", force: :cascade do |t|
t.string "name"
t.text "comment"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
create_table "uploadzips", force: :cascade do |t|
t.string "file_name"
t.string "file_type"
t.datetime "date"
t.integer "size"
t.integer "pages"
t.string "file_ident"
t.string "md5"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "campaign_id"
end
add_foreign_key "uploadzips", "campaigns"
app/controllers/campaign_controller.rb
class CampaignsController < ApplicationController
def index
@campaigns = Campaign.all.order("created_at DESC")
end
def new
@campaign = Campaign.new
end
def create
@campaign = Campaign.new(campaign_params)
if @campaign.save
flash[:success] = "Campaign Successfully Launched!"
redirect_to @campaign
else
flash[:error] = "There was a problem launching your Campaign."
redirect_to new_campaign_path
end
end
.....
private
def campaign_params
params.require(:campaign).permit(:name, :comment, :uploadzip_ids, uploadpdf_ids: [])
end
end
观看次数/广告系列/_form.rb
<%= form_for @campaign, url: {action: "create"} do |f| %>
.....some typical fields..
<%= f.label :data_file, class: "right-label" %>
<%= select_tag campaign[uploadzip_ids],
options_from_collection_for_select(
Uploadzip.all, :id, :file_name
), { include_blank: "Include a Zip File" } %>
.....some more typical fields
<% end %>
更新
我已更改代码以更好地反映建议的外键。创建活动现已成功,但与所选的uploadzip Zip 文件没有关联。调用@campaign.uploadzip 时,返回nil。
这是更新后的代码:
<%= select_tag "uploadzip[campaign_id]",
options_from_collection_for_select(
Uploadzip.all, :id, :file_name
), { include_blank: "Include a Zip File" } %>
我还把控制器params.require改成了..
def campaign_params
params.require(:campaign).permit(:name, :comment, :campaign_id, uploadpdf_ids: [])
end
【问题讨论】:
-
Uploadzip模型是否应该继承自ActiveRecord::Base? -
@Daiku - 它在源代码中。不太清楚在我的复制/粘贴中是如何删除的。
标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord actionview