根据活动名称提交歌曲

时间:2016-12-21 04:25:14

标签: ruby-on-rails

所以我有一个程序,我可以根据下拉菜单输入一首歌曲(艺术家,标题,流派),该菜单包含所有数据库事件名称。我怎么能传递对象事件名称,同时还满足了需要事件id将歌曲提交给该事件的要求。这是我的song_form:

<%= form_for @song do |f| %>
  <%= f.select :event_id, options_for_select(Event.all.collect{|c| [c.name, c.id]}, @song.event_id), :class => 'form-control' %>
  <%= f.text_field :artist %>
  <%= f.text_field :title %>
  <%= f.text_field :genre %>

  <%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>

歌曲控制器:

class SongsController < ApplicationController
    def new
        @song = Song.new
    end

    def create
        current_event = Event.find(params[:song][:event_id])
        @song = current_event.songs.build(song_params)
        if @song.save
            flash[:success] = "Success"
            redirect_to root_url
        else
            flash[:error] = "Failed"
        end

    end

    def destroy
    end
    private

      def song_params
        params.require(:song).permit(:event_id, :artist, :title, :genre)
      end
end

我有什么办法可以做到这一点。我不能在没有它的情况下为一个活动提交一首歌,如果你们可以帮我这个,那就太好了。)

1 个答案:

答案 0 :(得分:1)

在控制器的new操作中,定义实例变量@song = Song.new并将该变量用作form对象。因此,您可以在编辑歌曲时跟踪选定的Event。但是,如果您为newedit创建两个单独的视图表单,那么就可以了。

<%= form_for @song do |f| %>
    <%= f.select :event_id, options_for_select(Event.all.collect{|c| [c.name, c.id]}, @song.event_id), :class => 'form-control' %>
<% end %>

检查options_for_select

相关问题