使用check_box_tag在rails中传递额外的参数

时间:2014-02-23 19:54:11

标签: ruby-on-rails ruby ruby-on-rails-4

我想在填充Event模型的标准表单时添加一些额外的参数(类别)。它们不在我的事件表中(我在categories_eventshmbtm模型中都有表EventsCategory。这是我的_form代码:

<% @categories.each do |category| %>
  <div class="field">
  <%= check_box_tag(:category, category.id) %>
  <%= label_tag( :category, "#{category.name}" ) %>
  </div>

  <div class="actions">
    <%= f.submit %>

  <% end %> 

我在new行动中传递了类别 - 这是简单的Category.all

这是我在事件控制器中的代码

def new
    @event = Event.new
    @categories = Category.all
  end

def create
    @event = Event.new(event_params)
    @category_id = Category.find(params[:category])

    respond_to do |format|
      if @event.save
        format.html { redirect_to @event, notice: 'Event was successfully created.' }
        format.json { render action: 'show', status: :created, location: @event }
      else
        format.html { render action: 'new' }
        format.json { render json: @event.errors, status: :unprocessable_entity }
      end
    end
  end

后来我想将category_id和event_id放入categories_events中,但我有NoMethodError

undefined method `category_id' for #<Event:0x374c268>

和@ event.safe是问题

参数看起来像这样

{"utf8"=>"✓",
 "authenticity_token"=>"stL+sdIhxttrk3KjkLJsuCXubjaDpNBbrLYtpjv8clw=",
 "event"=>{"name"=>"asdsa",
 "place"=>"asdas",
 "description"=>"dsadsa"},
 "commit"=>"Create Event",
 "category"=>"2"}

我认为问题在于new(event_params)中的参数太多,但是查看参数中的括号会告诉我,使其适用于rails是不应该的。

错误堆栈跟踪: http://pastebin.com/kQK1fni6

更新了event_params

def event_params
      params.require(:event).permit(:name, :place, :description, :category_ids)
    end

2 个答案:

答案 0 :(得分:1)

将check_box_tag调整为以下内容:

<%= check_box_tag("event[category_ids][]", category.id, @event.categories.include?(category)) %>
<%= label_tag("event[category_ids][]", category.name) %>

还有一件事,你必须将category_ids添加到白名单属性中。

答案 1 :(得分:1)

要解决Couldn't find Category without an ID 替换

@category_id = Category.find(params[:category_ids]) 

@category_id = Category.find(params[:event][:category_ids]) 

如果您检查params哈希值,您会看到由于复选框代码中的更新(由H-man建议),category_ids将成为params[:event]键值的一部分