2016-04-01 3 views
1

У меня есть модель Пользователь с соотношением:Как сделать переменную видимой в макете?

belongs_to :freelancer 

и модель Freelancer с:

belongs_to :user. 

Для использования регистрации Devise. После регистрации новый пользователь автоматически создает объект Freelancer с user_id = current user.id. Как быть лучше мне получить @freelancer объект user_id = current user после знака вверх или знак в и передать в шаблон макета:

макеты/_user_panel.html.erb

<div class="user-panel_head"> 
    <%= link_to @freelancer, title: current_user.username, class: "user-panel__avatar active" do %> 
     <%= image_tag "default/avatar.png", class: "avatario" %> 
    <% end %> 
    <div class="user-panel__side"> 
     <%= link_to current_user.username, @freelancer, class: "user-panel__user-name" %> 
     <span class="btn_drop icon_arrow_up" role="expand_menu_trigger"></span> 
    </div> 
</div> 

UPDATE:

# == Schema Information 
# 
# Table name: users 
# 
# id      :integer   not null, primary key 
# email     :string   default(""), not null 
# encrypted_password  :string   default(""), not null 
# reset_password_token :string 
# reset_password_sent_at :datetime 
# remember_created_at :datetime 
# sign_in_count   :integer   default(0), not null 
# current_sign_in_at  :datetime 
# last_sign_in_at  :datetime 
# current_sign_in_ip  :string 
# last_sign_in_ip  :string 
# created_at    :datetime   not null 
# updated_at    :datetime   not null 
# confirmation_token  :string 
# confirmed_at   :datetime 
# confirmation_sent_at :datetime 
# unconfirmed_email  :string 
# failed_attempts  :integer   default(0), not null 
# unlock_token   :string 
# locked_at    :datetime 
# username    :string 
# 
# Indexes 
# 
# index_users_on_confirmation_token (confirmation_token) UNIQUE 
# index_users_on_email     (email) UNIQUE 
# index_users_on_reset_password_token (reset_password_token) UNIQUE 
# index_users_on_unlock_token   (unlock_token) UNIQUE 
# 

class User < ApplicationRecord 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    belongs_to :freelancer 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable 
end 

МОДЕЛЬ FREELANCER

# == Schema Information 
# 
# Table name: freelancers 
# 
# id    :integer   not null, primary key 
# first_name  :string 
# last_name  :string 
# rate   :integer 
# birthday  :date 
# location  :string 
# description :text 
# site   :string 
# visible  :boolean 
# avatar   :string 
# category_id :integer 
# created_at  :datetime   not null 
# updated_at  :datetime   not null 
# user_id  :integer 
# specialization :string 
# price_category :string 
# ownership  :string 
# 
# Indexes 
# 
# index_freelancers_on_category_id (category_id) 
# index_freelancers_on_user_id  (user_id) 
# 

class Freelancer < ApplicationRecord 
    belongs_to :category 
    belongs_to :user 
    has_many :links 
    has_and_belongs_to_many :payment_options 

    accepts_nested_attributes_for :links, allow_destroy: true 

    PRICE_CATEGORIES = ['Project', 'Hour', 'Month', 'For 1000 characters'] 
    OWNERSHIP_TYPES = ['Individual', 'Company'] 

ответ

1

Попробуйте это, он создаст Freelancer сразу после sign_up.

class User < ActiveRecord::Base 
    has_one :freelancer, dependent: :destroy 
    before_create :set_freelancer 

    def set_freelancer 
    build_freelancer(id: self.id, user_id: self.id, email: self.email) 
    end 
end 

class Freelancer < ActiveRecord::Base 
    belongs_to :user 
end 
+0

, если у вас были проблемы с ним, только что исправленный теперь должен работать. Также хорошая точка этого, Идентификаторы пользователя и фрилансера будут одинаковыми всегда. – 7urkm3n

1

В чем разница между current_user и @freelancer в этом примере? Вы заполняете свое представление данными от current_user, что означает, что они одни и те же объекты, так что вы не могли бы просто link_to current_user, ...?

Во всяком случае, чтобы задать точку вашего вопроса - переменные экземпляра в контроллере передаются в макеты так же, как и к шаблонам и частичным. Все они считаются взглядами и, как правило, ведут себя аналогичным образом. Таким образом, вам нужно будет установить @freelancer в контроллере в рамках любого действия, ответственного за рендеринг вашей страницы.

В случае Devise вы должны рассмотреть возможность переопределения метода after_sign_up_path_for и вернуть маршрут, по которому вы хотите, чтобы пользователь был перенаправлен после регистрации.

class Users::RegistrationsController < Devise::RegistrationsController 

    # Resource is a User in this case 
    def after_sign_up_path_for(resource) 
     super(resource) 

     user_path(resource) # Return the path for the `users#show` route 
    end 
    end 
end 

Таким образом, вы бы назначить @freelancer в действии контроллера, связанного с user_path. Тот же принцип применим и к Devise's SessionsController

+0

спасибо, Anthony –

Смежные вопросы