我正在尝试将模型Thing
与Thing
表单上的另一个things/new
相关联。每件事都有很多东西:连接表中的东西:related_things。
当我提交表单时,我收到此错误:
NoMethodError in ThingsController#create
undefined method `each' for "1":String
我的代码在哪里出错?
Thing
模型:我在行中添加了星号和错误消息。
class Thing < ActiveRecord::Base
has_many :related_things
has_many :things, :through => :related_things
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "30x30!" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
def related_things
related_thing_ids = RelatedThing.
where("thing_a_id = ? OR thing_b_id = ?", self.id, self.id).
map { |r| [r.thing_a_id, r.thing_b_id] }.
flatten - [self.id]
Thing.where(id: related_thing_ids)
end
def related_thing_ids=(ids)
***ids.each do |id|***
record = RelatedThing.where(thing_a_id: self.id, thing_b_id: id).first
record ||= RelatedThing.where(thing_a_id: id, thing_b_id: self.id).first
record ||= RelatedThing.create!(thing_a_id: self.id, thing_b_id: id)
end
end
end
RelatedThing
型号:
class RelatedThing < ActiveRecord::Base
has_many :things
end
Things
控制器:
class ThingsController < ApplicationController
def show
@thing = Thing.find(params[:id])
@related_thing = RelatedThing.all
@thing.things.build
end
def new
@thing = Thing.new
@things = Thing.all
end
def create
@thing = Thing.new(thing_params)
if @thing.save
redirect_to @thing
else
render 'new'
end
end
private
def thing_params
params.require(:thing).permit(:name, :avatar, :related_thing_ids)
end
end
观光/ new.html.erb:
<h1>Add Something!</h1>
<p>
<%= form_for @thing, :url => things_path, :html => { :multipart => true } do |f| %>
<%= f.text_field :name, :placeholder => "Name of the thing" %>
<br>
<%= f.label :related_things %>
<%= f.collection_select :related_thing_ids, Thing.all, :id, :name %>
<br>
<%= f.label :display_picture %>
<%= f.file_field :avatar %>
<br>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</p>
Schema.rb:
ActiveRecord::Schema.define(version: 20141016190146) do
create_table "related_things", force: true do |t|
t.integer "thing_a_id"
t.integer "thing_b_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "things", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
end
end
我正在使用Rails 4.0.10。
答案 0 :(得分:0)
尝试Array(ids).each ...
,它转换数组中的任何对象并响应:每个
~ (main) > Array(nil)
=> []
~ (main) > Array([])
=> []
~ (main) > Array('')
=> [""]
~ (main) > Array(1)
=> [1]
请参阅Kernel#Array