我正在创建一个项目,允许用户在登录后登录并引用其他用户。用户拥有多个推荐人和推荐人belongs_to用户。我想有一个页面,一旦当前用户登录,他们可以使用params:name和referral_email输入推荐。但这是一个协作项目,设置用户身份验证的人使用设计。目前,我收到以下错误:
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
答案 0 :(得分:1)
问题来自推介视图中的devise_error_messages!
- 将其删除。只有user
资源被设置为与设计一起使用,没有别的。
正如评论中所述,您应该重新考虑将推介作为用户下的嵌套资源 - 使用它的方式确实没有任何优势,并且有很多错误的余地。保持简单!