我有一个程序,允许用户为某个事件输入他们的歌曲。您必须输入该事件的partycode才能提交。以下是它的外观截图:
这是我的SongsController的样子:
class SongsController < ApplicationController
def new
@song = Song.new
end
def create
current_event = Event.find(song_params[:event_id])
@song = current_event.songs.build(song_params)
if @song.save
flash[:success] = "Success"
redirect_to event_path(@song.event)
else
flash[:error] = "Failed"
end
end
def destroy
end
private
def song_params
params.require(:song).permit(:event_id, :artist, :title, :genre)
end
end
事件模型
class Event < ApplicationRecord
belongs_to :user
validates :name, presence: true
validates :partycode, presence: true, length: {minimum: 5}
has_many :songs, dependent: :destroy
end
歌曲模型
class Song < ApplicationRecord
belongs_to :event
validates :artist, presence: true
validates :title, presence: true
end
new.html.erb(歌曲)
<br>
<br>
<h1> Member page </h1>
<div class ="container">
<div class="jumbotron">
<h2> Select an event to add songs to: </h2>
<%= form_for Song.new do |f| %>
<%= f.collection_select(:event_id, Event.all, :id, :name) %>
<h3> Enter your song </h3>
<%= form_for Song.new do |f| %>
<%= f.text_field :artist, placeholder: "Artist" %>
<%= f.text_field :title, placeholder: "Title" %>
<%= f.text_field :genre, placeholder: "Genre" %>
<h2> Enter the partycode for that event: </h2>
<%= form_for Event.new do |f| %>
<%= f.text_field :partycode %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
<% end %>
<% end %>
</div>
</div>
如何使我的网站的这项功能有效?非常感谢任何帮助
答案 0 :(得分:1)
我看到很多form_for嵌套在你的视图上。这是不可能的。只有一个提交表单。
我想您可能想要更改_form.html.erb
<div class ="container">
<div class="jumbotron">
<h2> Select an event to add songs to: </h2>
<%= form_for @song do |f| %>
<%= f.collection_select(:event_id, Event.all, :id, :name) %>
<h3> Enter your song </h3>
<%= f.text_field :artist, placeholder: "Artist" %>
<%= f.text_field :title, placeholder: "Title" %>
<%= f.text_field :genre, placeholder: "Genre" %>
<h2> Enter the partycode for that event: </h2>
<%= f.text_field :partycode %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</div>
</div>
答案 1 :(得分:1)
你完全搞砸了你的表格。理想情况下,您应该有一个表单,但在这里您只使用form_for
将一个表单保存在另一个表单中。
我建议你看一下form_for documentation
。