我正在創建一個項目,允許用戶在登錄後引用其他用戶。用戶擁有_many引薦和引薦belongs_to用戶。我想要一個頁面,一旦當前用戶登錄,他們就可以輸入參數:名稱和referral_email。但是這是一個合作項目,並且設置用戶認證的人使用了設計。目前,我發現了以下錯誤:創建belongs_to和has_many路由,控制器和視圖?
undefined method `resource' for #<ReferralsController:0x007fb75735aa00>
用戶控制器:
class UsersController < ApplicationController
def new
end
末
推薦控制器:
class ReferralsController < ApplicationController
def new
@referral = Referral.new
end
def create
@referral = current_user.referrals.new(referral_params)
if @referral.save
redirect_to @referral
else
render 'new'
end
end
def show
@referrals = current_user.find_by_user_id(params[:user_id]).referrals.all
end
def index
@referrals = current_user.referrals.all
end
def edit
@referral = Referral.find(params[:id])
end
def update
@referral = Referral.find(params[:id])
if @referral.update(referral_params)
redirect_to @referral
else
render 'edit'
end
end
def destroy
@referral = Referral.find(params[:id])
@referral.destroy
redirect_to referral_path
end
private
def referral_params
params.require(:referral).permit(:name, :email, :user_id)
end
end
用戶模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_many :referrals
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
include RoleModel
# attr_accessible :email, :password, :password_confirmation, :school_name, :sport, :roles, :roles_mask
roles_attribute :roles_mask
roles :admin, :coach, :guest
end
推薦型號
class Referral < ActiveRecord::Base
belongs_to :user
end
用戶視圖:
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %></div>
<div><%= f.label :school_name %><br />
<%= f.text_field :school_name %></div>
<div><%= f.label :sport %><br />
<%= f.text_field :sport %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password, autocomplete: "off" %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %></div>
<div><%= f.submit "Sign up" %></div>
<% end %>
<%= render "devise/shared/links" %>
推薦視圖:
<h2>Refer a coach </h2>
<%= form_for ([current_user, @referral]), :html => { :mulitpart => true } do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :referral %><br />
<%= f.text_field :referral %></div>
<div><%= f.label :referral_email %><br />
<%= f.email_field :referral, autofocus: true %></div>
<div><%= f.submit "Refer This Coach" %></div>
<% end %>
途徑:
Blog::Application.routes.draw do
devise_for :users
resources :users do
resources :referrals
end
get 'sessions/new'
get 'users/new'
resources :articles do
resources :comments
end
root 'welcome#index'
end
將「推介」作爲「用戶」下的嵌套路線移除。由於它始終適用於當前用戶,它應該是一個簡單的資源 - 不是嵌套的。此外,您的推介#顯示行動邏輯是可疑的,你可能想看看結束。 – PinnyM