使用嵌套模型的Rails强参数问题

时间:2017-09-07 16:50:52

标签: ruby-on-rails ruby forms activerecord

我正在尝试在已有的用户展示页面上呈现new视图。在尝试提交此视图时,我得到param is missing or the value is empty: user。要清楚这是技能部分在用户显示页面上呈现。出于某种原因,它在我的用户控制器中使用了强大的参数。

代码:

show.html.erb for user

<h4>Create a Skill</h4>
<%= render partial: "skills/form" %>

userscontroller.rb

def show
    @user = User.find(params[:id])
    @skill = Skill.new
    @skills = @user.skills.all
  end

  private

  def user_params
    params.require(:user).permit(:username, :password, :avatar_url, :email, :about, :cover_letter, :city, :state)
  end
end

SkillsController.rb

class SkillsController < ActionController::Base
  def new
    user = User.find(params[:user_id])
    @skill = user.skills.new
  end

  def create
    user = User.find(params[:user_id])
    @skill = user.skills.new(skill_params)
    if @skill.save
      flash[:message] = "#{@skill.name} skill has been created!"
      redirect_to user_path(user)
    else
      redirect_to new_user_skill_path
    end
  end

  private

  def skill_params
    params.require(:skill).permit(:name, :level)
  end
end

另外,我在用户中拥有Namespaced技能。尚未进行身份验证。

编辑:@nickm,这里是技巧/ _form

的内容
<%= simple_form_for(Skill.new, :url => { :action => "create" })  do |f| %>
  <%= f.input :name, label: 'Skill Name ' %>
  <%= f.input :level, label: "Skill Level ", collection: ["Beginner","Proficient", "Intermediate", "Advanced", "Expert"], include_blank: false, include_hidden: false %>

  <%= f.submit %>
<% end %>

1 个答案:

答案 0 :(得分:1)

问题是您没有通过表单传递user_id。您必须添加表单输入:

<%= f.hidden_field :user_id, some_value %>

然后找到用户:

user = User.find(params[:skill][:user_id])

然后制作skill_params

def skill_params
  params.require(:skill).permit(:name, :level, user_id)
end

或者可选地,在控制器操作中设置user_id的值。由于尚未构建任何身份验证,因此不确定如何传递该值。如果你使用的是devise,你可以做

current_user.skills.new(skills_params)

...在你的创作中。