0
我在Rails中有一對多關聯。歌曲有很多頻道和頻道屬於歌曲。我正在嘗試創建一個包含6個頻道的新歌曲。這是我在前端的形式:Rails一對多關聯,使用post ajax添加數據給許多人
$.ajax({
type : "POST",
url: ,url
dataType : 'json',
data : $("#form").serialize(),
success : function(data) {
var newSong = new Object();
newSong.song_name = data.sn;
newSong.singer_name = data.ss;
newSong.genre = data.sg;
newSong.channels[0].url=data.u1;
newSong.channels[1].url=data.u2;
newSong.channels[2].url=data.u3;
newSong.channels[3].url=data.u4;
newSong.channels[4].url=data.u5;
newSong.channels[5].url=data.u6;
},
error : function(result) {
console.log(result);
},})});});
</script>
</head>
<body>
<form id="form" action="" method="post">
Song Name: <input id="sn" type="text" name="song_name"><br><br>
Singer Name: <input id="ss" type="text" name="singer_name"><br><br>
Genre: <input id="sg" type="text" name="genre"><br><br>
Url 1: <input id="u1" type="text" name="url"><br><br>
Url 2: <input id="u2" type="text" name="url"><br><br>
Url 3: <input id="u3" type="text" name="url"><br><br>
Url 4: <input id="u4" type="text" name="url"><br><br>
Url 5: <input id="u5" type="text" name="url"><br><br>
Url 6: <input id="u5" type="text" name="url"><br><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
正如你可以從我的代碼中看到我的表單字段名爲url的所有輸入和引起該問題,但是當我改名字尾部不承認它是允許的parameter.Here是我的歌曲控制器創建行動:
def create
@song = Song.new(song_params)
@song.save
@ch1 = Channel.new(channel_params1)
@[email protected]
@ch1.save
@ch2 = Channel.new(channel_params2)
@[email protected]
@ch2.save
@ch3 = Channel.new(channel_params3)
@[email protected]
@ch3.save
@ch4 = Channel.new(channel_params4)
@[email protected]
@ch4.save
@ch5 = Channel.new(channel_params5)
@[email protected]
@ch5.save
@ch6 = Channel.new(channel_params6)
@ch6[email protected]
@ch6.save
respond_to do |format|
if @ch6.save
format.html { redirect_to @song, notice: 'Song was successfully created.' }
format.json { render :show, status: :created, location: @song }
else
format.html { render :show }
format.json { render json: @song.errors, :status => :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def song_params
params.permit(:song_name, :singer_name , :genre)
end
def channel_params1
params.permit(:url)
end
def channel_params2
params.permit(:url)
end
def channel_params3
params.permit(:url)
end
def channel_params4
params.permit(:url)
end
def channel_params5
params.permit(:url)
end
def channel_params6
params.permit(:url)
end
end
注:我的行動是成功的設定一個網址,但所有6個頻道的網址設定爲最後的形式入境,所以我得到相同的網址全部6
問題是我沒有使用視圖部分的鋼軌我正在使用前端jQuery和對該部分作出反應。 –
啊,好吧。這就說得通了。這裏的訣竅是使用名稱中的索引構建輸入名稱。例如''Rails會將其作爲url列表提取到參數中,類似於'{「url」=> [, ...]} –
jaydel