UsersController Method Error 'title'. No Title in view? - ruby-on-rails

Reposting due to formatting errors in previous post.
I am getting the below error, I've added code below for the whole MVC. The strange thing here is the controller wants a 'title' method to be included but I don't have a title requirement anywhere else, could this be referring to something else. While this isn't working the def update method won't patch so I can't save any user updates or new data to the system (it's a HRIS system btw).
So the error is;
NoMethodError in UsersController#update
undefined method `title' for #<User:0x007ff3dd9f8a70>
Extracted source (around line #56):
54
55
56
57
58
59
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Information Updated"
redirect_to #user
#handle successful update
Here is my Schema;
create_table "users", force: :cascade do |t|
t.string "name"
t.string "employee"
t.string "email"
t.string "password"
t.date "startdate"
t.date "probationcomp"
t.date "annualreview"
t.text "address"
t.string "phonenumber"
t.string "nextofkin"
t.string "kinnumber"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.boolean "admin", default: false
t.string "leavenum"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
t.boolean "hstrain"
t.boolean "induction"
t.boolean "lhtrain"
t.boolean "vodatotal"
t.boolean "commtrainops"
t.boolean "commtrainsell"
t.boolean "hosttrainops"
t.boolean "hosttrainsell"
t.boolean "cpstrainops"
t.boolean "cpstops"
t.boolean "cpstsell"
t.string "leaverem"
t.text "specialism"
t.string "shelf"
t.string "doc_file_name"
t.string "doc_content_type"
t.integer "doc_file_size"
t.datetime "doc_updated_at"
end
The view;
<h1>Change your profile settings</h1>
<div class="row">
<%= form_for #user do |f| %>
<%= render 'shared/error_messages' %>
<!-- left side -->
<div class="col-md-6">
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<%= f.label :address, "Home Address" %>
<%= f.text_area :address, :cols => "1", :rows => "5", class: "form-control" %>
</div>
<!-- right side -->
<div class="col-md-6">
<%= f.label :phonenumber, "Contact Number" %>
<%= f.text_field :phonenumber, class: "form-control" %>
<%= f.label :nextofkin, "Emergency Contact Person" %>
<%= f.text_field :nextofkin, class: "form-control" %>
<%= f.label :kinnumber, "Emergency Contact Phone Number" %>
<%= f.text_field :kinnumber, class: "form-control" %>
<div class="gravatar_edit">
<%= gravatar_for #user %>
<a href="https://gravatar.com/emails" target=_blank>Change Profile Pic</a>
</div><br><p><br>
<%= f.submit "Save Changes", class: 'btn btn-warning' %>
<% end %>
</div>
</div>
The controller (this is where I think the error is, though update function looks fine, I haven't posted the whole controller, but can do if it helps)
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Information Updated"
redirect_to #user
#handle successful update
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :employee, :email, :password, :startdate, :probationcomp,
:password_confirmation, :annualreview, :address, :phonenumber, :nextofkin, :kinnumber,
:created_at, :updated_at, :password_digest, :admin, :leavenum, :avatar_file_name, :avatar_content_type, :avatar_file_size,
:avatar_updated_at, :hstrain, :induction, :lhtrain, :vodatotal, :commtrainops, :commtrainsell, :hosttrainops,
:hosttrainsell, :cpstrainops, :cpstops, :cpstsell, :leaverem, :specialism, :shelf, :doc_file_name, :doc_content_type,
:doc_file_size, :doc_updated_at)
end
Finally the model;
class User < ApplicationRecord
attr_accessor :remember_token
before_save { email.downcase! }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 7 }, allow_nil: true
#set up "uploaded_file" field as attached_file (using Paperclip)
searchable do
text :name, :id, :phonenumber
end
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::password.create(string, cost: cost)
end
def User.new_token
SecureRandom.urlsafe_base64
end
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
def authenticated?
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
def forget
update_attribute(:remember_token, nil)
end
end
I'm sure someone has had this issue before, just can't see the wood for the trees. test script comes back with same error.

Related

ActiveRecord::RecordNotFound in WorkersController#create

now i'm doing creating a worker with role. I have worker , role and worker_role. Now i have done the create worker form and have a selection to choose role. After done the form i need to role_id and worker_id store in worker_role table. I have try and it return me some error.
worker controller
def new
#worker = Worker.new
#worker.company_id = params[:company_id]
#role = Role.all
end
def create
#worker = Worker.new(worker_params)
#company_id = Company.find(params[:worker][:company_id])
#role_id = Role.all
if #worker.save
#worker_role = Role.find(params[:id]).worker_roles.create(worker: worker, returned: true)
#log_in #worker
flash[:success] = "Welcome to the Areca Supermarket System!"
redirect_to #worker
else
render 'new'
end
end
new.html.erb(the form)
<% provide(:title, "Register worker") %>
<h1>Create Worker</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: #worker, local: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.label :phone_number %>
<%= f.number_field :phone_number, class: 'form-control' %>
<%= f.label :address %>
<%= f.text_field :address, class: 'form-control' %>
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :role_id %>
<%= f.select(:role_id, Role.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.hidden_field :company_id , value: 2%>
<%= f.submit "Create worker", class: "btn btn-primary" %>
<% end %>
</div>
</div>
worker_role model
class WorkerRole < ApplicationRecord
belongs_to :worker
belongs_to :role
end
worker_role migration
create_table "worker_roles", force: :cascade do |t|
t.integer "worker_id"
t.integer "role_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
worker migration
create_table "workers", force: :cascade do |t|
t.string "name"
t.string "email"
t.integer "phone_number"
t.string "address"
t.integer "company_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.boolean "admin", default: false
end
Error show in website
parameter in website
Hi as mentioned in request params, I can see that role_id you are passing in params as
Parameters:
params = {"authenticity_token"=>"[FILTERED]",“worker"=>{"name"=>"Daniel", "“email"=:“daniel#example.com", “phone_number"=:"Q134657891",“address"=>"Alor Setar", “password"=>"[FILTERED]", “role id"=>"1", “company _id"=:"2",“commit"=>"Create worker"}
#you can access the role ID as below:
params[:worker][:role_id]
But you are using it in the controller as
#worker_role = Role.find(params[:id])
#this should be as below:
#worker_role = Role.find(params[:worker][:role_id]).worker_roles.create(worker: #worker)
# OR
#if you are permitting role id
#worker_role = Role.find(worker_params[:role_id]).worker_roles.create(worker: #worker)

Rails: How to store a JSON object from a form and query it?

I am new to rails and am in need of help. I want my new post form to allow users to copy and paste the text from a JSON file into a text_area and have it stored as a JSON object in my Postgresql database. Then I want to be able to query the JSON object in the rails console or just in psql.
Here is my form:
<h1>New Post</h1>
<hr>
<div align="center"><%= form_for (#post) do |f| %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title, :required => true %>
</div>
<br>
<div class="field">
<%= f.label :description %>
<%= f.text_area :description, :required => true %>
</div>
<br>
<div class="field">
<%= f.file_field :json, :required => true %>
<%= f.hidden_field :json_cache %>
</div>
<br>
<div class="field">
<%= f.label "JSON" %>
<%= f.text_area :data, :required => true %>
<%= f.hidden_field :user_id , :value => current_user.id %>
</div>
<br>
<%= f.hidden_field :user_id , :value => current_user.id %>
<div class="actions">
<%= f.submit %>
</div>
<% end %></div>
Here is my posts controller:
class PostsController < ApplicationController
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
#post.update_attributes(post_params)
redirect_to post_path(#post)
end
def new
#post = Post.new
#post.user_id = current_user.id
end
def index
#posts = Post.all
end
def show
#post = Post.find_by_id(params[:id])
end
def create
#post = Post.new(post_params)
if #post.save
flash[:success] = "Success!"
redirect_to post_path(#post)
else
flash[:error] = #post.errors.full_messages
redirect_to new_post_path
end
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to new_post_path
end
private
def post_params
params.require(:post).permit( :json, :description, :title, :data, :user_id )
end
end
Here is my db schema:
ActiveRecord::Schema.define(version: 20161127203635) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "posts", force: :cascade do |t|
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "title"
t.integer "user_id"
t.string "json"
t.json "data"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name"
t.string "last_name"
t.string "username"
t.date "birthday"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
end
When I go to query the JSON that is in my database, I don't get anything in return.
I do: psql mydatabase
Then I tried: SELECT data->>'name' AS name FROM posts
But it doesn't return anything.
Here's a JSON file that should be stored in my DB in the :data column:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
So what am I doing wrong? I need to be able to query the JSON.
Form your post params like this
def post_params
params.require(:post).permit(:description, :title, :user_id, json: {}, data: {})
end

Error: has-many relationship in form, duplicate data when update

I am doing an e-commerce.
I have products which have many options of products and at the same time they only have one variant.
I try to make the view to create the product have the option of add a block where appears the fields of the model and the changes of the variant which is associated to it. The problem is, for example, when i create a product with 5 options, when i update it increases to 10, and if i update it again, there will be 20. I can't find the problem why they are duplicating. I leave the codes below.
Schema of Product, option-product and variant
create_table "options_products", force: :cascade do |t|
t.integer "product_id"
t.float "price"
t.integer "stock"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "products", force: :cascade do |t|
t.string "name", default: "", null: false
t.text "description"
t.integer "category_id"
t.integer "vendor_id"
t.string "state", null: false
t.boolean "shippingInside", null: false
t.datetime "created_at"
t.datetime "updated_at"
t.integer "priceComparison"
t.string "image1_file_name"
t.string "image1_content_type"
t.integer "image1_file_size"
t.datetime "image1_updated_at"
t.float "price"
end
create_table "variants", force: :cascade do |t|
t.string "tipoVariant"
t.integer "options_product_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "controlStock"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
end
Script for add and remove fields
$(document).on 'ready page:load', ->
$('form').on 'click', '.remove_field', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
$('form').on 'click', '.add_field', (event) ->
time = new Date().getTime()
regular_expression = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regular_expression,time))
event.preventDefault()
Product create and update
def create
#product = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product}
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product}
format.json { render :show, status: :ok, location: #product }
else
format.html { render :edit }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
Product Params
def product_params
params.require(:product).permit(:name, :description, :state, :shippingInside, :vendor_id, :category_id, :priceComparison, :image1, :price, offer_attributes: [:status], options_products_attributes: [:price, :stock, variant_attributes: [:tipoVariant, :controlStock, :image]])
function in application helper to add association
def link_to_add_association(name, field, association)
new_object = field.object.send(association).klass.new
new_object_id = new_object.object_id
fields = field.fields_for(association, new_object, child_index: new_object_id) do |builder|
new_object.build_variant
render(association.to_s.singularize + '_field', f: builder)
end
link_to(name, '#', class: 'add_field', data: { id: new_object_id, fields: fields.gsub("\n", "") })
end
Product model
class Product < ActiveRecord::Base
#relations
belongs_to :category
belongs_to :vendor
has_one :offer, :dependent => :destroy
has_many :options_products, :dependent => :destroy
#accepts
accepts_nested_attributes_for :offer, allow_destroy: true
accepts_nested_attributes_for :options_products, allow_destroy: true
#validations
validates :name, presence:true
validates :name, uniqueness:true
validates :state, presence:true
validates :category_id, presence:true
validates :vendor_id, presence:true
has_attached_file :image1, styles: {medium: "300x300>", thumb: "150x150#" }
validates_attachment_content_type :image1, content_type: /\Aimage\/.*\z/
end
Option Product Model
class OptionsProduct < ActiveRecord::Base
belongs_to :product
has_one :variant, :dependent => :destroy
accepts_nested_attributes_for :variant, allow_destroy: true
end
Variant model
class Variant < ActiveRecord::Base
belongs_to :options_product
has_attached_file :image,
styles: {medium: "300x300>", thumb: "150x150#" }
validates_attachment_content_type :image,
content_type: /\Aimage\/.*\z/
end
_form of Product
= form_for #product, html: { multipart: true } do |f|
.row
.form-group.col-lg-6
.field
= f.file_field :image1
.row
.form-group.col-lg-6
.field
= f.text_field :name, :placeholder => 'Nombre', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.text_area :description, :placeholder => 'Descripcion', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.number_field :price, :placeholder => 'Precio a mostrar', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.label :Estado
%br/
= f.select :state, options_for_select(['Disponible', 'No disponible'])
.row
.form-group.col-lg-6
.field
= f.label :Envio
%br/
= f.check_box :shippingInside
.row
.form-group.col-lg-6
.field
= f.text_field :priceComparison, :placeholder => 'Precio anterior', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.label :vendor_id
%br/
= f.select :vendor_id, Vendor.all.collect { |vendor| [vendor.name, vendor.id] }
.row
.form-group.col-lg-6
.field
= f.label :category_id
%br/
= f.select :category_id, Category.all.collect { |category| [category.name, category.id] }
= f.fields_for :offer, #product.build_offer do |o|
= o.label :Oferta
%br/
= o.check_box :status
%br/
.row
= f.fields_for :options_products do |op|
= render 'options_product_field', f: op
= link_to_add_association 'Agregar variante', f, :options_products
%br/
.actions
= f.submit "Enviar", :class => 'button btn btn-primary bold'
options_product_field file
%fieldset
.row
.form-group.col-lg-6
.field
= f.text_field :price, :placeholder => 'Precio', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.text_field :stock, :placeholder => 'Stock', :class => 'form-control input-border-left'
= f.fields_for :variant do |v|
.row
.form-group.col-lg-6
.field
= v.text_field :tipoVariant, :placeholder => 'Tipo de variante', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= v.label :ControlarStock
%br/
= v.check_box :controlStock
.row
.form-group.col-lg-6
.field
= v.label :ImagenDeVariante
%br/
= v.file_field :image
= f.hidden_field :_destroy
= link_to 'Remover variante', '#', class: 'remove_field'
In product_params, you should specify id of options_products_attributes. Without id, attributes will be newly added to product model.
So, try
... options_products_attributes: [ :id, price, :stock, variant_attributes: [ :id, :tipoVariant, ...

Render email in stead of user_id but with 2 custom ids on the record - Ruby On Rails

Im a bit new to Ruby on Rails so I'm hoping this isn't a stupid question.
I'm trying to make an application to store played fifa games.
This requires 2 users linked to one game, but offcourse one user can also have many games, therefore I used a many-to-many relation.
Controller:
class GamesController < ApplicationController
before_action :authenticate_user!, exept: [:index, :show]
def index
#games = Game.all
end
def new
#game = current_user.games.build
#user_options = User.all.map{|u| [ u.email, u.id ] }
end
def create
#user_options = User.all.map{|u| [ u.email, u.id ] }
#game = Game.new(game_params)
#game.home_team_user_id = current_user.id
#game.home_team_user_name = current_user.email
if #game.save
redirect_to games_path, :notice => "Successfully added game!"
else
render 'index'
end
end
def show
#games = Game.all
end
def destroy
#game = Game.find(params[:id])
#game.destroy
redirect_to games_path
end
private
def find_game
#game = Game.find(params[:id])
end
def game_params
params.require(:game).permit(:home_team_user_name, :home_score, :away_team_user_name, :away_score, :home_team_user_id, :away_team_user_id)
end
end
View File:
<div class="panel panel-default" style="margin-left: 10px; margin-right:10px">
<!-- Default panel contents -->
<div class="panel-heading">Played games</div>
<!-- Table -->
<table class="table">
<thead>
<th>Home Team</th>
<th>Home Team Score</th>
<th>Away Team Score</th>
<th>Away Team</th>
<th>Added by</th>
<th>Actions</th>
</thead>
<% #games.each do |game|%>
<tbody>
<td>
<%= game.home_team_user_id %>
</td>
<td>
<%= game.home_score %>
</td>
<td>
<%= game.away_score %>
</td>
<td>
<%= game.away_team_user_id %>
</td>
<td>
</td>
<td>
<%= link_to "Delete", game, method: :delete, data: { confrim: "Are you sure?"} %>
</td>
<% end %>
</tbody>
</table>
</div>
New Game form:
<div class="col-md-12" style="text-align:center">
<div class="panel panel-default" style="margin-right:10px">
<div class="panel-heading">
<h3 class="panel-title">Submit New Match</h3>
</div>
<div class="panel-body">
<%= simple_form_for(#game) do |f| %>
<%= f.text_field :home_score, :placeholder => "Your score" %>
<%= f.text_field :away_score, :placeholder => "Your Opponents score" %>
<%= f.select(:away_team_user_id, #user_options) %>
<%= f.submit "Submit Match", class: "btn-submit" %>
<% end %>
<!-- <%= form_for #game do |f| %>
<%= collection_select(:game, :away_team_user_id, User.all, :id, :email, prompt: true ) %>
<%= f.text_field :home_score, :placeholder => "Your score" %>
<%= f.text_field :away_score, :placeholder => "Your Opponents score" %>
<%= f.submit "Submit Match", class: "btn-submit" %>
<% end %> -->
</div>
</div>
Now I'm able to add games with the
home_team_user_id = current_user
away_team_user_id = user selected from dropdown menu
and offcourse the score.
However in the view the email adresses should be shown in stead of the id's.
I've tried many solutions like <%= game.home_team_user_id.user.email %>
This gives the error : undefined method `user' for 1:Fixnum
Can anybody help me on this mather? What am I doing wrong?
Thx in advance!
ADDITIONAL QUESTION:
Hi there so I tried the last answer but I'm getting an error.
undefined local variable or method `game' for
Controller:
class GamesController < ApplicationController
before_action :authenticate_user!, exept: [:index, :show]
def index
#games = Game.all
#home_user = User.select(:id, :user_name).find(game.home_team_user_id)
end
def new
#game = current_user.games.build
#user_options = User.all.map{|u| [ u.user_name, u.id ] }
end
def create
#user_options = User.all.map{|u| [ u.user_name, u.id ] }
#game = Game.new(game_params)
#game.home_team_user_id = current_user.id
if #game.home_score > #game.away_score
#game.winner_id = #game.home_team_user_id
#game.loser_id = #game.away_team_user_id
else
#game.winner_id = #game.away_team_user_id
#game.loser_id = #game.home_team_user_id
end
if #game.save
redirect_to games_path, :notice => "Successfully added game!"
else
render 'index'
end
end
def show
#games = Game.all
end
def destroy
#game = Game.find(params[:id])
#game.destroy
redirect_to games_path
end
private
def find_game
#game = Game.find(params[:id])
end
def game_params
params.require(:game).permit(:home_team_user_name, :home_score, :away_team_user_name, :away_score, :home_team_user_id, :away_team_user_id, :winner_id, :loser_id)
end
end
Models:
Game:
class Game < ActiveRecord::Base
has_many :user_games
has_many :users, through: :user_games
belongs_to :winner, class_name: 'User' # or Team or whatever
belongs_to :loser, class_name: 'User'
before_validation :evaluate_score!, if: -> { home_score.present? }
private
def evaluate_score!
self.winner = home_score > away_score ? home_team_user : away_team_user
self.loser = home_score < away_score ? home_team_user : away_team_user
end
end
User:
class User < ActiveRecord::Base
has_many :user_games
has_many :games, through: :user_games
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
user_game:
class UserGame < ActiveRecord::Base
belongs_to :game
belongs_to :user
end
Schema:
ActiveRecord::Schema.define(version: 20160331142037) do
create_table "game_users", force: :cascade do |t|
t.integer "user_id_id"
t.integer "game_id_id"
end
create_table "games", force: :cascade do |t|
t.string "home_team_user_name"
t.string "home_score"
t.string "away_team_user_name"
t.string "away_score"
t.integer "home_team_user_id"
t.integer "away_team_user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "winner_id"
t.integer "loser_id"
end
create_table "user_games", force: :cascade do |t|
t.integer "user_id"
t.integer "game_id"
t.integer "user_id_id"
t.integer "game_id_id"
end
add_index "user_games", ["game_id_id"], name: "index_user_games_on_game_id_id"
add_index "user_games", ["user_id_id"], name: "index_user_games_on_user_id_id"
create_table "users", force: :cascade do |t|
t.string "user_name"
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "win"
t.integer "los"
t.integer "draw"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
In your controller, try:
#home_user = User.select(:id, :email).find(game.home_team_user_id)
In your view:
<%= #home_user.email %>
Thanks for the comment, this worked for me:
<%= User.find(game.home_team_user_id).email %>
I am guessing you have a has_many relation in the model, then in your view you should use:
<% game.home_team_users.each do |home_team| %>
<%= home_team.email %>
<% end %>
Added:
I am going to ignore that you are using #games = Game.all in def show, which is the same as in def index. :)
The show should display view only related to one record, and index should be used for all records

Rails: How do I select the current user instead of all the users? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How do I make it automatically pull up the current users name when I go to the user profile page. Like I click on the "message me" button and instead of pulling all the users on the site, I want it to pull automatically the user I am looking at.
Right now when I press the "message me" button it pulls up all the users and I have to choose which user to send the message. What can I do? I can use <%= user.name %> to pull up the user but that isn't going to help me.
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#exampleModal" data-whatever="<%= #user.name%>">Message Me</button>
<%= f.collection_select (:recipients, User.all.collect {|p| [ p.name, p.id ] }, {}, { multiple: true , class: "chosen-select form-control" })%>
Full code:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<%= form_for :conversation, url: :conversations, html: { class: "" } do |f| %>
<div class="panel2-signup">
<div class="panel-body-signup">
<div class="modal-body">
<form>
<div class="form-group">
To <%= f.collection_select (:recipients, User.all.collect {|p| [ p.name, p.id ] }, {}, { multiple: true , class: "chosen-select form-control" })%>
Subject:
<%= f.text_field :subject, class: "form-control" %>
Message:
<%= f.text_area :body, class: 'form-control', placeholder: "Type your message here", rows: 4 %>
</div>
</div>
Here is the db info
class CreateMailboxer < ActiveRecord::Migration
def self.up
#Tables
#Conversations
create_table :mailboxer_conversations do |t|
t.column :subject, :string, :default => ""
t.column :created_at, :datetime, :null => false
t.column :updated_at, :datetime, :null => false
end
#Receipts
create_table :mailboxer_receipts do |t|
t.references :receiver, :polymorphic => true
t.column :notification_id, :integer, :null => false
t.column :is_read, :boolean, :default => false
t.column :trashed, :boolean, :default => false
t.column :deleted, :boolean, :default => false
t.column :mailbox_type, :string, :limit => 25
t.column :created_at, :datetime, :null => false
t.column :updated_at, :datetime, :null => false
end
#Notifications and Messages
create_table :mailboxer_notifications do |t|
t.column :type, :string
t.column :body, :text
t.column :subject, :string, :default => ""
t.references :sender, :polymorphic => true
t.column :conversation_id, :integer
t.column :draft, :boolean, :default => false
t.string :notification_code, :default => nil
t.references :notified_object, :polymorphic => true
t.column :attachment, :string
t.column :updated_at, :datetime, :null => false
t.column :created_at, :datetime, :null => false
t.boolean :global, default: false
t.datetime :expires
end
#Indexes
#Conversations
#Receipts
add_index "mailboxer_receipts","notification_id"
#Messages
add_index "mailboxer_notifications","conversation_id"
#Foreign keys
#Conversations
#Receipts
add_foreign_key "mailboxer_receipts", "mailboxer_notifications", :name => "receipts_on_notification_id", :column => "notification_id"
#Messages
add_foreign_key "mailboxer_notifications", "mailboxer_conversations", :name => "notifications_on_conversation_id", :column => "conversation_id"
end
def self.down
#Tables
remove_foreign_key "mailboxer_receipts", :name => "receipts_on_notification_id"
remove_foreign_key "mailboxer_notifications", :name => "notifications_on_conversation_id"
#Indexes
drop_table :mailboxer_receipts
drop_table :mailboxer_conversations
drop_table :mailboxer_notifications
end
end
The ConversationsController.rb
class ConversationsController < ApplicationController
before_action :authenticate_user!
before_action :get_mailbox
def new
end
def index
end
def create
recipients = User.where(id: conversation_params[:recipients])
if
conversation = current_user.send_message(recipients, conversation_params[:body], conversation_params[:subject]).conversation
flash[:notice] = "Your message was successfully sent!"
redirect_to conversation_path(conversation)
else
flash[:alert] = "Error. Message was not created"
redirect_to new_conversation_path
end
end
def show
#receipts = conversation.receipts_for(current_user).order("created_at ASC")
# mark conversation as read
conversation.mark_as_read(current_user)
end
def reply
current_user.reply_to_conversation(conversation, message_params[:body])
flash[:notice] = "Your reply message was successfully sent!"
redirect_to conversation_path(conversation)
end
def trash
conversation.move_to_trash(current_user)
redirect_to mailbox_inbox_path
end
def untrash
conversation.untrash(current_user)
redirect_to mailbox_inbox_path
end
def delete
#mailbox.trash.each do |conversation|
conversation.receipts_for(current_user).update_all(deleted: true)
end
flash[:notice] = 'Your trash was cleaned!'
redirect_to mailbox_inbox_path
end
private
def conversation_params
params.require(:conversation).permit(:subject, :body,recipients:[])
end
def get_mailbox
#mailbox ||= current_user.mailbox
if #user = current_user
#post = current_user.posts.build
else
end
if #user = current_user
#post = current_user.posts.build
#purchased = Sale.where(buyer_email: current_user.email).order("created_at DESC").order("created_at DESC").paginate(page:params[:page], per_page: 1 )
#sales = Sale.where(seller_email: current_user.email).order("created_at DESC").order("created_at DESC").paginate(page:params[:page], per_page: 1 )
else
end
end
def message_params
params.require(:message).permit(:body, :subject)
end
end
Looking at your action filters it looks like you are using the devise gem for user management.
To get the current authenticated user in devise you can use the helper method current_user.

Resources