强大的参数值

时间:2015-01-21 14:02:14

标签: ruby-on-rails ruby parameters

如何从控制器手动插入参数值, 这是我的控制器

def new
  @new_post = Post.new(params[:title])
end

def create
  @new_post = Post.new(new_post_params)
  if @new_post.save
    flash[:success] = 'Post created!'
    redirect_to home_url
  else
    flash[:danger] = @new_post.errors.full_messages.to_sentence
    redirect_to home_url
  end
end

private
def new_post_params
  params.require(:post).permit(
    :title, 
    poster_id: current_user.id, 
    poster_name: current_user.name
 )

我的表单视图

form_for @new_post do |f|
   f.text_area :title
end

累了使用这种方法,poster_id和poster_name仍然是空白

    def new_post_params
      params.require(:post).permit(
      :title, 
      poster_id: current_user.id, 
      poster_name: current_user.name
   )
   end

2 个答案:

答案 0 :(得分:2)

试试这个

params.require(:post).permit(:title).merge(
  { 
    poster_id: current_user.id,
    poster_name: current_user.name
  }
)

答案 1 :(得分:0)

   def new_post_params
     params[:post][:poster_id] = current_user.id
     params[:post][:poster_name] = current_user.name 
     params.require(:post).permit(
        :title, 
        :poster_id,
        :poster_name
      )     
   end