无法创建新的邀请记录

时间:2017-11-25 03:29:04

标签: ruby-on-rails

我似乎无法理解为什么我的邀请控制器中的create方法不会创建新记录。我之前只从表单发送过params,在这种情况下,它来自link_to。我认为我的问题来源于观点。

视图:

<div class="title"> Invite <%= @user.name %> </div>
<div class="invitations"> Which event would you like to invite <%= @user.name %> to? </div>

<div class="panel panel-primary">
  <% @events.events.each do |f|  %>
  <div class="panel-body">
  <%= link_to f.title, controller: "invitations",
                       action: :create,
                       user_id: f.id,
                       method: :post %> </div>
  <% end %>
</div>

控制器:

class InvitationsController < ApplicationController

def index
end 

def new 
    @user = User.find(params[:id])
    @events = current_user
    @invitation = Invitation.new
end

def create
  @invitation = Invitation.new(invitation_params)
  if @invitation.save 
    flash[:info] ="Invitation sent"
    redirect_to root_path
  else
  flash[:info] = "Something went wrong"
  redirect_to root_path 
  end 
end 

def show
end 

private

def invitation_params
  params.permit(:user_id)
end

end

路线:

Rails.application.routes.draw do
  get 'attendances/create'
  get 'invitations/create'
  resources :attendances
  resources :events
  resources :static_pages
  resources :users
  resources :invitations
  root 'static_pages#index'
  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'

end

日志:

Started GET "/invitations/create?method=post&user_id=4" for 127.0.0.1 at 2017-11-24 22:28:00 -0500
Processing by InvitationsController#create as HTML
  Parameters: {"method"=>"post", "user_id"=>"4"}
Unpermitted parameter: :method
   (0.2ms)  begin transaction
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 4], ["LIMIT", 1]]
   (0.4ms)  rollback transaction
Redirected to http://localhost:3000/
Completed 302 Found in 1564ms (ActiveRecord: 1.0ms)

1 个答案:

答案 0 :(得分:0)

您只允许user_id中的invitation_params

由于link_to帮助程序的语法无效,因此method: :post作为参数添加:

  

参数:{&#34;方法&#34; =&gt;&#34;发布&#34;,&#34; user_id&#34; =&gt;&#34; 4&#34;}

因此消息:

  

未经许可的参数::方法

尝试使用路径,而不是在link_to中指定控制器和操作:

<%= link_to f.title, invitations_path(user_id: f.id), method: :post %>

这也有效,但代码更多:

<%= link_to user.name, { controller: 'users', action: 'create', user_id: f.id }, method: :post %>

这不起作用:

<%= link_to user.name, users_path, { user_id: f.id, method: :post } %>
# => Unpermitted parameters: :_method, :authenticity_token