I am receiving undefined method on `message_time' for nil:NilClass:
Showing /home/ubuntu/workspace/app/views/conversations/index.html.erb where line #19 raised:
undefined method `message_time' for nil:NilClass
Extracted source (around line #19):
17
18
19
20
21
22
<div class="col-md-2">
<%= other.fullname %><br>
19 <%= conversation.messages.last.message_time %>
</div>
<div class="col-md-8">
<%= conversation.messages.last.content %>
app/views/conversations/index.html.erb
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Your conversations</div>
<div class="panel-body">
<div class="container">
<% #conversations.each do |conversation| %>
<% other = conversation.sender == current_user ? conversation.recipient : conversation.sender %>
<%= link_to conversation_messages_path(conversation) do %>
<div class="row conversation">
<div class="col-md-2">
<%= image_tag avatar_url(other), class: "img-circle avatar-medium" %>
</div>
<div class="col-md-2">
<%= other.fullname %><br>
<%= conversation.messages.last.message_time %>
</div>
<div class="col-md-8">
<%= conversation.messages.last.content %>
</div>
</div>
<% end %>
<% end %>
</div>
</div>
</div>
<h3>All Users</h3>
<% #users.each do |user| %>
<% if user != current_user %>
<%= user.fullname %>
<%= link_to "Send Message", conversations_path(sender_id: current_user.id, recipient_id: user.id), method: 'post' %>
<% end %>
<br>
<% end %>
</div>
Conversation controller
class ConversationsController < ApplicationController
before_action :authenticate_user!
def index
#users = User.all
#conversations = Conversation.involving(current_user)
end
def create
if Conversation.between(params[:sender_id], params[:recipient_id]).present?
#conversation = Conversation.between(params[:sender_id], params[:recipient_id]).first
else
#conversation = Conversation.create(conversation_params)
end
redirect_to conversation_messages_path(#conversation)
end
private
def conversation_params
params.permit(:sender_id, :recipient_id)
end
end
Conversation.rb
class Conversation < ActiveRecord::Base
belongs_to :sender, foreign_key: :sender_id, class_name: 'User'
belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User'
has_many :messages, dependent: :destroy
validates_uniqueness_of :sender_id, scope: :recipient_id
scope :involving, -> (user) do
where("conversations.sender_id = ? OR conversations.recipient_id = ?", user.id, user.id)
end
scope :between, -> (sender_id, recipient_id) do
where("(conversations.sender_id = ? AND conversations.recipient_id = ?) OR (conversations.sender_id = ? AND conversations.recipient_id = ?)",
sender_id, recipient_id, recipient_id, sender_id)
end
end
I think conversation has no messages and so conversation.messages.last is nil.
You are calling message_time on a nil object and that's what the error message says. Before calling message_time, make sure converation.messages is not empty. You could solve this by
<% messages = conversation.messages %>
<%= messages.last.message_time unless messages.empty? %>
Other option is
<% messages = conversation.messages %>
<%= messages.last.try(:message_time) %>
Related
I am having trouble debugging this error. NoMethodError in Products#Index undefined method 'id' for #ActiveRecord::Relation
Here is my products controller:
class ProductsController < ApplicationController
def index
if params[:query].present?
#products = Product.search_by_name_and_category(params[:query])
else
#products = Product.all
end
end
def new
#product = Product.new
#product.user = current_user
end
def show
#product = Product.find(params[:id])
end
end
Here is my product model:
class Product < ApplicationRecord
belongs_to :user
has_many :bookings
validates :name, presence: true
validates :category, presence: true
has_one_attached :photo
include PgSearch::Model
pg_search_scope :search_by_name_and_category,
against: [ :name, :category ],
using: {
tsearch: { prefix: true } # <-- now `superman batm` will return something!
}
end
This is my product-card partial.
<div class="card-product-container">
<div class="cards">
<div class="card-product">
<%= link_to product_path(#products.id) do %>
<img src="https://source.unsplash.com/random/?<%= product.name %>" />
<div class="card-product-footer">
<div>
<h2><%= product.name %></h2>
<p><%= product.category %></p>
</div>
<h2><%= product.price %></h2>
</div>
<% end %>
</div>
</div>
#products is a list of many Products. The list doesn't have an ID. Each Product in the list does.
You instead want the ID of a each individual Product in #products.
Iterate through #products and work with a single Product.
<% #products.each do |product| %>
<div class="card-product">
<%= link_to product_path(product.id) do %>
<img src="https://source.unsplash.com/random/?<%= product.name %>" />
<% end %>
<div class="card-product-footer">
<div>
<h2><%= product.name %></h2>
<p><%= product.category %></p>
</div>
<h2><%= product.price %></h2>
</div>
</div>
<% end %>
I am using carrierwave and trying to display images of products in the index view. This are my models, controllers and views
product.rb
class Product < ActiveRecord::Base
has_many :order_items
belongs_to :category, required: false
has_many :product_attachments
accepts_nested_attributes_for :product_attachments
mount_uploader :image, ImageUploader
default_scope { where(active: true) }
end
product_attachment.rb
class ProductAttachment < ApplicationRecord
mount_uploader :image, ImageUploader
belongs_to :product
end
products_controller.rb (extract)
class ProductsController < ApplicationController
def index
#products = Product.all
#order_item = current_order.order_items.new
end
def show
#product = Product.find(params[:id])
#product_attachments = #product.product_attachments.all
end
def new
#product = Product.new
#product_attachment = #product.product_attachments.build
#categories = Category.all.map{|c| [ c.name, c.id ] }
end
def create
#product = Product.new(product_params)
#product.category_id = params[:category_id]
respond_to do |format|
if #product.save
params[:product_attachments]['image'].each do |a|
#product_attachment = #product.product_attachments.create!(:image => a, :product_id => #product.id)
end
format.html { redirect_to #product, notice: 'Product was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
private
def product_params
params.require(:product).permit(:name,:price, :active, :description, product_attachments_attributes:
[:id, :product_id, :image], category_attributes: [:category_id, :category])
end
end
index.html.erb
<div class="row">
<div class="col-xs-offset-1 ">
<% #products.each do |product| %>
<%= render "product_row", product: product, order_item: #order_item %>
<% end %>
</div>
_product_row.html.erb
<div class="well">
<div class="row">
<div class="container-fluid row">
<div class="col-md-5 col-lg-5 col-sm-5 col-xs-5 binder">
<br><%= image_tag product.image_url.to_s %><br><br>
</div>
<div class="col-md-4 col-lg-4 col-sm-4 col-xs-4 binder">
<h4 class="text-left"><%= product.name.split.map(&:capitalize).join(' ') %> </h4>
<h4 class="text-left"><span style="color: green"><%= number_to_currency(product.price, :unit => "€") %></span></h4>
<h4><%= link_to Category.find(product.category_id).name, category_path(product.category_id) %></h4>
<h6 class="text-left"><%= link_to 'Delete', product_path(product), method: :delete,
data: { confirm: 'Are you sure?' } %></h6><br><br>
</div>
<div class="col-md-3 col-lg-3 col-sm-3 col-xs-3 binder">
<%= form_for order_item, remote: true do |f| %>
<div class="input-group">
<%= f.number_field :quantity, value: 1, class: "form-control", min: 1 %>
<div class="input-group-btn">
<%= f.hidden_field :product_id, value: product.id %>
<%= f.submit "Add to Cart", class: "btn btn-primary text-right" %>
</div>
</div>
<% end %>
</div>
</div>
</div>
</div>
With <%= image_tag product.image_url.to_s %> the image doesn't appear. When I change it to <%= image_tag product_attachments.first.image_url.to_s %> I get the following error:
undefined local variable or method `product_attachments' for #<#<Class:0x00007f28544ccc68>:0x00007f285dd3aab8>
I am pretty new to Ruby and don't know what I am doing wrong or how to fix this. Any help would be appreciated. I am using Ruby version 2.5.1 and rails 5.2.0 on ubuntu.
I would expect that the following works:
<%= image_tag product.product_attachments.first.image_url.to_s %>
Try this:
image_tag(product.product_attachments.first.image.url.to_s)
It should work. I realized that sometimes image_url doesn't work as expected but image.url does.
If i understand well your snippets, the model you mount the ImageUploader is ProductAttachment (which have the attribute image) so you can remove mount_uploader :image, ImageUploader of your Product model.
The image is mounted on every product_attachments for one product. Just display the images inside the partial by iterating through product_attachments:
<% product.product_attachments.each do |attachment| %>
<%= image_tag(attachment.image.url) %>
<% end %>
i have a problem with my form who contains multiple object
When i go on my page "new" for create new team_member, i have this error :
unknown attribute 'team_member_id' for TeamMembersGame.
models/team_member.rb
class TeamMember < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
has_many :team_members_games
accepts_nested_attributes_for :team_members_games
has_many :team_members_weapons
has_many :team_members_champions
end
models/team_member_game.rb
class TeamMembersGame < ActiveRecord::Base
belongs_to :team_member
end
controllers/admin/team_members_controller.rb
class Admin::TeamMembersController < Admin::DashboardController
def new
#member = TeamMember.new
#member.team_members_games.build
end
def create
#member = TeamMember.new(member_params)
if #member.save
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été creer'
else
render 'new'
end
end
def edit
#member = TeamMember.find(params[:id])
#member_game = #member.team_members_games
##member = TeamMember.joins(:TeamMembersChampion, :TeamMembersWeapon, :TeamMembersGame)
end
def update
#member = TeamMember.find(params[:id])
if #member.update_attributes(member_params)
# Handle a successful update.
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été modifier'
else
render 'edit'
end
end
def destroy
TeamMember.destroy(params[:id])
redirect_to admin_team_members_path, notice: 'Le membre a bien ete supprimer'
end
private
def member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games: [ :team_members_id, :name_game])
end
def member_games
params.require(:team_members_games).permit(:team_members_id, :name_game)
end
end
view/admin/new.html.erb
<%= form_for(#member, url: admin_team_members_path, html: { method: :post }, id: 'new_news') do |f| %>
<%= #member.inspect %>
<%= #member_games.inspect %>
<div class="row">
<div class="col s12">
<% #member.errors.full_messages.each do |msg| %>
<%= msg %>
<% end %>
</div>
</div>
<div class="row">
<div class="col s12 m6">
<div class="field input-field">
<%= f.label :name, "Nom" %>
<%= f.text_field :name, autofocus: true, :class => "" %>
</div>
</div>
</div>
<div class="row">
<div class="col s12">
<p class="bold">
Jeux :
</p>
</div>
<div class="col s12 m6">
<%= f.fields_for :team_members_games do |team_members_games_form| %>
<div class="field input-field">
<%= team_members_games_form.check_box :name_game, {:class => "filled-in", :id => "team_members_game_name_game"}, true, false %>
<%= team_members_games_form.label :name_game, "game" %>
</div>
<% end %>
</div>
</div>
<div class="row">
<div class="col s12">
<div class="btnlog actions">
<%= button_tag(type: 'submit', class: "btn") do %>
Publier <i class='material-icons right'>send</i>
<% end %>
</div>
</div>
</div>
<% end %>
thanks !
you are permitting team_members_id in your code instead of team_member_id
refactor your code to this:
def member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games_attributes: [ :id, :team_member_id, :name_game])
end
Change permitted method name and parameters like this:-
def team_member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games: [ :id, :name_game])
end
And use this method while creating team member:-
def create
#member = TeamMember.new(team_member_params)
if #member.save
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été creer'
else
render 'new'
end
end
I have corrige some errors, but i haven't idea for get the id of team_member for the table team_member_games :
def team_member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_game_attributes: [ :id, :name_game])
end
no one element are add in my table team_members_games
How can we DESC order results according to its :date_value in the quantifieds index?
Results being the nested attribute to quantifieds.
Right now the order is according to where the User added the result in the form, regardless of :date_value.
This has proven more difficult than I would have guessed.
class QuantifiedsController < ApplicationController
before_action :set_quantified, only: [:show, :edit, :update, :destroy]
before_action :logged_in_user, only: [:create, :destroy]
def index
if params[:tag]
#quantifieds = Quantified.tagged_with(params[:tag])
else
#quantifieds = Quantified.joins(:results).all
#averaged_quantifieds = current_user.quantifieds.averaged
#instance_quantifieds = current_user.quantifieds.instance
end
end
def show
end
def new
#quantified = current_user.quantifieds.build
end
def edit
end
def create
#quantified = current_user.quantifieds.build(quantified_params)
if #quantified.save
redirect_to quantifieds_url, notice: 'Quantified was successfully created'
else
#feed_items = []
render 'pages/home'
end
end
def update
if #quantified.update(quantified_params)
redirect_to quantifieds_url, notice: 'Goal was successfully updated'
else
render action: 'edit'
end
end
def destroy
#quantified.destroy
redirect_to quantifieds_url
end
private
def set_quantified
#quantified = Quantified.find(params[:id])
end
def correct_user
#quantified = current_user.quantifieds.find_by(id: params[:id])
redirect_to quantifieds_path, notice: "Not authorized to edit this goal" if #quantified.nil?
end
def quantified_params
params.require(:quantified).permit(:categories, :metric, :result, :date, :tag_list, results_attributes: [:id, :result_value, :date_value, :_destroy])
end
end
class Quantified < ActiveRecord::Base
belongs_to :user
has_many :results #correct
accepts_nested_attributes_for :results, :reject_if => :all_blank, :allow_destroy => true #correct
scope :averaged, -> { where(categories: 'Averaged') }
scope :instance, -> { where(categories: 'Instance') }
validates :categories, :metric, presence: true
acts_as_taggable
CATEGORIES = ['Averaged', 'Instance']
end
class Result < ActiveRecord::Base
belongs_to :user
belongs_to :quantified
end
class CreateQuantifieds < ActiveRecord::Migration
def change
create_table :quantifieds do |t|
t.string :categories
t.string :metric
t.references :user, index: true
t.timestamps null: false
end
add_foreign_key :quantifieds, :users
add_index :quantifieds, [:user_id, :created_at]
end
end
class CreateResults < ActiveRecord::Migration
def change
create_table :results do |t|
t.string :result_value
t.date :date_value
t.integer :quantified_id
t.timestamps null: false
end
end
end
form
<%= javascript_include_tag "quantified.js" %>
<%= simple_form_for(#quantified) do |f| %>
<%= f.error_notification %>
<div class="america">
<form>
<% Quantified::CATEGORIES.each do |c| %>
<%= f.radio_button(:categories, c, :class => "date-format-switcher") %>
<%= label(c, c) %>
<% end %>
<br/>
<br/>
<div class="form-group">
<%= f.text_field :tag_list, quantified: #quantified.tag_list.to_s.titleize, class: 'form-control', placeholder: 'Enter Action' %>
</div>
<div class="form-group">
<%= f.text_field :metric, class: 'form-control', placeholder: 'Enter Metric' %>
</div>
<div id="results">
<%= f.fields_for :results do |result| %>
<%= render 'result_fields', :f => result %>
<% end %>
</div>
<div class="links">
<b><%= link_to_add_association 'Add Result', f, :results %></b>
</div>
<div class="america2">
<%= button_tag(type: 'submit', class: "btn") do %>
<span class="glyphicon glyphicon-plus"></span>
<% end %>
<%= link_to quantifieds_path, class: 'btn' do %>
<span class="glyphicon glyphicon-chevron-left"></span>
<% end %>
<%= link_to #quantified, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn' do %>
<span class="glyphicon glyphicon-trash"></span>
<% end %>
</div>
</form>
</div>
<% end %>
index
<!-- Default bootstrap panel contents -->
<div id="valuations" class="panel panel-default">
<div class="panel-heading"><h4><b>AVERAGE</b></h4></div>
<% #averaged_quantifieds.each do |averaged| %>
<div class="attempt">
<b><%= raw averaged.tag_list.map { |t| link_to t.titleize, tagquantifieds_path(t) }.join(', ') %>
<%= link_to edit_quantified_path(averaged) do %>
(<%= averaged.metric %>)</b>
<% end %>
<ul>
<% averaged.results.each do |result| %>
<li>
<b><%= result.result_value %></b>
<%= result.date_value.strftime("%b %Y") %>
</li>
<% end %>
</ul>
</div>
<% end %>
</div>
<div class="valuations-button">
<%= link_to new_quantified_path, class: 'btn' do %>
<b><span class="glyphicon glyphicon-plus"</span></b>
<% end %>
</div>
<br>
<!-- Default bootstrap panel contents -->
<div id="valuations" class="panel panel-default">
<div class="panel-heading"><h4><b>INSTANCE</b></h4></div>
<% #instance_quantifieds.each do |instance| %>
<div class="attempt">
<b><%= raw instance.tag_list.map { |t| link_to t.titleize, tagquantifieds_path(t) }.join(', ') %>
<%= link_to edit_quantified_path(instance) do %>
(<%= instance.metric %>)</b>
<% end %>
<ul>
<% instance.results.each do |result| %>
<li>
<%= result.date_value.strftime("%b.%d.%y") %>
<%= result.result_value %>
</li>
<% end %>
</ul>
</div>
<% end %>
</div>
<div class="valuations-button">
<%= link_to new_quantified_path, class: 'btn' do %>
<b><span class="glyphicon glyphicon-plus"</span></b>
<% end %>
</div>
Thanks so much for your time!
Got it! Add default_scope { order('date_value DESC') } in result.rb
I have this on my view:
<div class='container'>
<div class='row upper_container'>
<div class='search_container'>
<%= form_tag deals_path, :method => :get, :class => 'navbar-form navbar-left' do %>
<div class='form-group'>
<%= text_field_tag :search, params[:search], class: 'form-control' %>
</div>
<%= submit_tag 'Search', :name => nil %>
<% end %>
</div>
</div>
<% #deals.each_with_index do |d, i| %>
<% if i % 3 == 0 %>
<div class='row middle_container'>
<% end %>
<div class='col-md-4'>
<div class='deal_container'>
<%= d.title %>
<img src='<%= d.photo %>', class='deal_img'>
</div>
</div>
<% if (i % 3 == 2) || (i == (#deals.length - 1)) %>
</div>
<% end %>
<% end %>
</div>
this in my controller:
class DealsController < ApplicationController
def index
# #deals = Deal.paginate(:page => params[:page])
#search = Deal.search do
fulltext params[:search]
end
#deals = #search.result
end
private
def deal_params
params.require(:deal).permit(:title)
end
end
and this in my model:
class Deal < ActiveRecord::Base
searchable do
text :title
end
end
when I want to do a seach by some word, like 'Treatment', the #deals variable, in the controller is null, but the param is being sent: Parameters: {"utf8"=>"✓", "search"=>"Treatment"}
any idea?
Try this:
query = params[:search]
#search = Deal.search do
fulltext query
end
#deals = #search.result
Please check this answer for details.