Rails 4 - 分配属性时,必须将哈希作为参数传递

时间:2014-12-05 22:52:57

标签: ruby-on-rails-4

任何人都可以帮我弄明白为什么我会收到以下错误吗?

When assigning attributes, you must pass a hash as an argument.

表格:

    <%= form_for([current_user, current_user.suggestions.build]) do |f| %>
        <%= f.label :category %>:
        <%= f.select :category, ['Startup', 'Cars', 'Kids', 'Food', 'Other'] %> <br>
        <%= f.text_area :suggestion %><br>
        <%= f.submit 'Submit Suggestion' %>
    <% end %>

SuggestionController:

  def create
    @suggestion = current_user.suggestions.create(suggestion_params)
  end

  private
    def suggestion_params
      params.require(:suggestion).permit(:suggestion, :category)
      redirect_to shirts_path
    end

的ApplicationController:

  helper_method :current_user

  private

    def current_user
      @current_user ||= User.find(session[:user_id]) if session[:user_id]
    end

1 个答案:

答案 0 :(得分:2)

suggestion_params返回方法redirect_to shirts_path的最后一行,current_user.suggestions.create无法接受,因为这是不可接受的数据。

重定向应采用create方法:

def create
    @suggestion = current_user.suggestions.create(suggestion_params)
    redirect_to shirts_path
end

private
  def suggestion_params
    params.require(:suggestion).permit(:suggestion, :category)
  end