我还没有解决这个问题,我有2个型号,播放列表和歌曲 播放列表模型
class PlayList < ActiveRecord::Base
has_and_belongs_to_many :songs
#rest of code
end
迁移表
class AddPlayListSong < ActiveRecord::Migration
def up
create_table :play_lists_songs, :id => false do |t|
t.references :play_list, :song
end
add_index :play_lists_songs, [:play_list_id, :song_id]
end
def down
drop_table :play_lists_songs
end
end
我正在尝试将歌曲添加到现有播放列表中(该歌曲已经存在),所以我在更新操作上执行了此操作,这是将歌曲添加到播放列表的表单
我的观点是歌曲/节目中的部分内容
<% @play_lists.each do |play_list| %>
<%=form_for play_list, url: users_play_list_path(play_list.id), method: :put, remote: :true do |f|%>
<ul>
<li>
<%=link_to "", class: "js_update_playlist", id:"play_list" do %>
<span class="count">(<%=play_list.song_ids.count%>)</span> <%=play_list.name%>
<%=f.hidden_field :song_ids, :value=>song.id%>
<%end %>
</li>
</ul>
<%end %>
“js_update_playlist”是一个javascript提交功能 我的控制器
def update
@play_list = current_user.play_lists.find(params[:id])
params[:play_list][:song_ids]
respond_to do |format|
if @play_list.update_attributes(params[:play_list])
format.js
end
end
end
我的问题是,这会删除现有的ID并将其替换为params song_ids,如下所示:
Selector Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."type" IN ('Selector') AND "users"."id" = 1 LIMIT 1
PlayList Load (0.5ms) SELECT "play_lists".* FROM "play_lists" WHERE "play_lists"."user_id" = 1 AND "play_lists"."id" = $1 LIMIT 1 [["id", "82"]]
(0.2ms) BEGIN
Song Load (0.5ms) SELECT "songs".* FROM "songs" WHERE "songs"."id" = $1 LIMIT 1 [["id", 4]]
Song Load (1.5ms) SELECT "songs".* FROM "songs" INNER JOIN "play_lists_songs" ON "songs"."id" = "play_lists_songs"."song_id" WHERE "play_lists_songs"."play_list_id" = 82
(0.4ms) DELETE FROM "play_lists_songs" WHERE "play_lists_songs"."play_list_id" = 82 AND "play_lists_songs"."song_id" IN (5)
(0.3ms) INSERT INTO "play_lists_songs" ("play_list_id", "song_id") VALUES (82, 4)
[paperclip] Saving attachments.
(37.8ms) COMMIT
我想加载所有play_list的song_ids并将song.id添加到此数组