我想在我的應用程序中一個帖子有很多位置(通過locations_posts表)執行find_or_create函數(類似於here)。不幸的是,代碼似乎執行,找到正確的記錄,然後繼續創建一個新的記錄,導致記錄重複。任何想法爲什麼會發生這種情況?使用Find_or_Create創建重複的模型
Post.rb
class Post < ActiveRecord::Base
before_save :get_locations
# ===============
# = Before Save =
# ===============
def get_locations
self.locations = self.locations.collect do |location|
Location.find_or_create_by(name: location[:name])
end
end
# =================
# = Associations =
# =================
has_many :location_post
has_many :locations, :through => :location_post
accepts_nested_attributes_for :locations
posts_controller.rb
class PostsController < ::Blogit::ApplicationController
...
def create
@post = current_blogger.blog_posts.new(valid_params)
if @post.save
redirect_to @post, notice: t(:blog_post_was_successfully_created, scope: 'blogit.posts')
else
render action: "new"
end
end
日誌
Parameters: {"utf8"=>"✓", "authenticity_token"=>"n4s...uAHATBRG1Nk=", "post"=>{"title"=>"Lorem ipsum dolor sit am
et", "body"=>"Consectetur adipiscing elit. Duis in diam in massa aliquet venenatis. Donec eleifend sed magna rutrum sagittis.", "locations_attributes"=>{"1402420506265"=>{"name"=>"London", "_destroy"=>"false"}}}, "commit"=>"Submit"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Unpermitted parameters: _destroy
(0.3ms) BEGIN
Location Load (0.6ms) SELECT "locations".* FROM "locations" WHERE "locations"."name" = 'London' LIMIT 1
SQL (0.5ms) INSERT INTO "blog_posts" ("blogger_id", "blogger_type", "body", "created_at", "title", "updated_at") VALUES ($1, $2, $3, $4, $
5, $6) RETURNING "id" [["blogger_id", 1], ["blogger_type", "User"], ["body", "Consectetur adipiscing elit. Duis in diam in massa aliquet ven
enatis. Donec eleifend sed magna rutrum sagittis."], ["created_at", "2014-06-10 17:15:09.564257"], ["title", "Lorem ipsum dolor sit amet"], [
"updated_at", "2014-06-10 17:15:09.564257"]]
SQL (0.4ms) INSERT INTO "locations" ("created_at", "name", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", "2014-06-10 1
7:15:09.566659"], ["name", "London"], ["updated_at", "2014-06-10 17:15:09.566659"]]
SQL (0.4ms) INSERT INTO "location_posts" ("created_at", "location_id", "post_id", "updated_at") VALUES ($1, $2, $3, $4) [["created_at", "
2014-06-10 17:15:09.568250"], ["location_id", 376], ["post_id", 83], ["updated_at", "2014-06-10 17:15:09.568250"]]
SQL (0.3ms) INSERT INTO "location_posts" ("created_at", "location_id", "post_id", "updated_at") VALUES ($1, $2, $3, $4) [["created_at", "
2014-06-10 17:15:09.571852"], ["location_id", 1], ["post_id", 83], ["updated_at", "2014-06-10 17:15:09.571852"]]
(0.7ms) COMMIT
請在get_locations方法中顯示self.locations內容。 – tebayoso
嗨@JorgedelosSantos,抱歉不知道你的意思? –
在執行get_location循環之前顯示自我對象的內容。 self.inspect並放置內容。 – tebayoso