我目前正在构建一个rails应用程序,用户可以登录仪表板并填写表单。我一直收到这个错误:
NoMethodError in Users#index
Showing C:/Users/xxx/Desktop/Sites/form-app/app/views/users/_dashboard_nav.html.erb where line #7 raised
undefined method `organization' for #<User:0x0000000c3e4de0>
UsersController.rb
class UsersController < ApplicationController
before_action :authenticate_user!
def index
@user = current_user
# @organization = current_user.organization.all
end
def show
end
end
_dashboard_nav.html.erb
...
<% if @user.organization.exists? %> <-- This is line 7
<%= link_to "Profile", edit_user_organization_path(@user, @organization), class: "dashboard-nav__item" %>
<% else %>
<%= link_to "Profile", new_user_organization_path(@user, @organization), class: "dashboard-nav__item" %>
<% end %>
...
organization.rb
class Organization < ActiveRecord::Base
belongs_to :user
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :organizations
has_many :form_submissions
end
答案 0 :(得分:0)
如果一个用户可以拥有多个组织,那么条件检查应该是
if @user.organizations.exists?
答案 1 :(得分:0)
你可以摆脱实例变量@user
。此外,您应该使用organizations
代替organization
控制器:
class UsersController < ApplicationController
before_action :authenticate_user!
def index
# do nothing here
end
# other methods
end
查看:
<% if current_user.organizations.exists? %>
<%= link_to "Profile", edit_user_organization_path(current_user, @organization), class: "dashboard-nav__item" %>
<% else %>
<%= link_to "Profile", new_user_organization_path(current_user, @organization), class: "dashboard-nav__item" %>
<% end %>