I am new to spree and ruby on rails.While clicking the 'reviews' in spree back-end, it's throwing an error.
Thanks in Advance.
NoMethodError in Spree::Admin::Reviews#index
Showing - var/lib/gems/2.3.0/ruby/2.3.0/bundler/gems/spree_reviews-e51cae9627f9/app/views/spree/admin/reviews/index.html.erb where line #25 raised:
index.html.erb:
<% content_for :page_title do %>
<%= Spree.t('reviews') %>
<% end %>
<% render 'spree/admin/shared/product_sub_menu' %>
<% content_for :table_filter_title do %>
<%= Spree.t('search') %>
<% end %>
<% content_for :table_filter do %>
<div data-hook="admin_reviews_index_search">
<%= search_form_for [:admin, #search] do |f| %>
<div class="alpha three columns">
<div class="field">
<%= label_tag nil, Spree.t(:user) %><br />
<%= f.text_field :name_cont, :size => 25 %>
</div>
</div>
<div class="seven columns">
<div class="field">
<%= label_tag nil, Spree.t(:title) -%><br/>
<%= f.text_field :title_cont, :size => 25 -%>
</div>
</div>
<div class="four columns">
<div class="field">
<%= label_tag nil, Spree.t(:review) -%><br/>
<%= f.text_field :review_cont, :size => 25 -%>
</div>
</div>
<div class="two columns omega">
<div class="field">
<%= label_tag nil, Spree.t(:approval_status)-%><br/>
<%= f.select :approved_eq, [[Spree.t('all'), nil],
[Spree.t('approved_reviews'), true],
[Spree.t('unapproved_reviews'),false]] -%>
</div>
</div>
<div class="clear"></div>
<div class="form-buttons actions filter-actions" data-
hook="admin_reviews_index_search_buttons">
<%= button Spree.t(:search), 'icon-search' %>
</div>
<%- end -%>
</div>
<%- end -%>
<% paginate #reviews %>
<% if #reviews.any? %>
<table class="index">
<colgroup>
<col style="width: 25%;">
<col style="width: 10%;">
<col style="width: 10%;">
<col style="width: 20%;">
<col style="width: 15%;">
<col style="width: 17%;">
</colgroup>
<thead>
<tr>
<th><%= Spree.t('product') %></th>
<th><%= Spree::Review.human_attribute_name(:rating) %></th>
<th><%= Spree.t('feedback') %></th>
<th><%= Spree::Review.human_attribute_name(:user) %></th>
<th><%= Spree::Review.human_attribute_name(:created_at) %></th>
</tr>
</thead>
<tbody>
<%- #reviews.each do |review| -%>
<tr id="<%= dom_id review %>">
<td>
<% if review.product %>
<%= link_to review.product.name, product_path(review.product) %>
<% end %>
</td>
<td class="align-center">
<%= txt_stars(review.rating) %>
</td>
<td class="align-center">
<%= link_to "(#{review.feedback_stars}/#{review.feedback_reviews.size})", admin_review_feedback_reviews_path(review) %>
</td>
<td class="align-center">
<%= review.user_id ? link_to(review.user.try(:email), [:admin, review.user]) : Spree.t(:anonymous) %></p>
<p><%= Spree::Review.human_attribute_name(:ip_address) %>: <%= review.ip_address ? link_to(review.ip_address, "http://whois.domaintools.com/#{review.ip_address}") : '-' %></p>
</td>
<td class="align-center">
<%= l review.created_at, :format => :short %>
</td>
<td class="actions">
<%= link_to_with_icon 'check', Spree.t('approve'), approve_admin_review_url(review), :no_text => true, class: 'approve' unless review.approved %>
<%= link_to_edit review, :no_text => true, :class => 'edit' %>
<%= link_to_delete review, :no_text => true %>
</td>
</tr>
<% end %>
</tbody>
</table>
<% else %>
<div class="no-objects-found">
<%= Spree.t(:no_results) %>
</div>
<% end %>
<%= paginate #reviews -%>
reviews_controller
class Spree::Admin::ReviewsController <
Spree::Admin::ResourceController
helper Spree::ReviewsHelper
def index
#reviews = collection
params[:q] ||= {}
#search = Spree::Review.ransack(params[:q])
#collection = #search.result.includes([:product, :user,
:feedback_reviews]).page(params[:page]).per(params[:per_page])
end
def approve
r = Spree::Review.find(params[:id])
if r.update_attribute(:approved, true)
flash[:notice] = Spree.t("info_approve_review")
else
flash[:error] = Spree.t("error_approve_review")
end
redirect_to admin_reviews_path
end
def edit
if #review.product.nil?
flash[:error] = Spree.t("error_no_product")
redirect_to admin_reviews_path and return
end
end
private
def collection
params[:q] ||= {}
#search = Spree::Review.ransack(params[:q])
#collection = #search.result.includes([:product, :user,
:feedback_reviews]).page(params[:page]).per(params[:per_page])
end
end
review.rb
class Spree::Review < ActiveRecord::Base
belongs_to :product, touch: true
belongs_to :user, :class_name => Spree.user_class.to_s
has_many :feedback_reviews
after_save :recalculate_product_rating, :if => :approved?
after_destroy :recalculate_product_rating
validates :name, presence: true
validates :review, presence: true
validates :rating, numericality: { only_integer: true,
greater_than_or_equal_to: 1,
less_than_or_equal_to: 5,
message: Spree.t('you_must_enter_value_for_rating') }
default_scope { order("spree_reviews.created_at DESC") }
scope :localized, ->(lc) { where('spree_reviews.locale = ?', lc) }
scope :most_recent_first, -> { order('spree_reviews.created_at DESC') }
scope :oldest_first, -> { reorder('spree_reviews.created_at ASC') }
scope :preview, -> { limit(Spree::Reviews::Config[:preview_size]).oldest_first }
scope :approved, -> { where(approved: true) }
scope :not_approved, -> { where(approved: false) }
scope :default_approval_filter, -> { Spree::Reviews::Config[:include_unapproved_reviews] ? all : approved }
def feedback_stars
return 0 if feedback_reviews.size <= 0
((feedback_reviews.sum(:rating) / feedback_reviews.size) + 0.5).floor
end
def set_search
#search=Product.search(params[:q])
end
def recalculate_product_rating
self.product.recalculate_rating if product.present?
end
end
Try to add result method after ransack:
#search = Spree::Review.ransack(params[:q]).result
Related
I have tags on my video objects. I can submit tags when creating a new video via my form however they don't appear on my video show page, video index or video edit form, which makes me think they are not being presisted to the database but I'm unclear on what I as missing or doing wrong.
models/video.rb
class Video < ActiveRecord::Base
after_create { validates_presence_of :user, :post }
belongs_to :user
belongs_to :post
has_many :comments
validates :title, presence: true
acts_as_taggable
end
views/videos/index.html.erb
<%= will_paginate #videos %>
<div class="" id="tag_cloud">
<% tag_cloud Video.tag_counts.sort { |x, y| x.name <=> y.name }, %w[s m l] do |tag, css_class| %>
<%= link_to tag.name, tag_path(tag.name), class: css_class %>
<% end %>
</div>
<div class="">
<% #videos.each do |video| %>
<div class="">
<%= link_to video.title, video_path(video) %></br >
<%= content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{video.embed_id}") %>
<p>Created by: <%= video.user.username %>, at: <%= video.created_at.strftime("%e, %b, %Y, %H:%M:%S %p") %></p>
<% unless video.comments.last.nil? %>
<%= video.comments.last.body %>
<% end %>
<p>
Tags: <%= raw video.tag_list.map { |t| link_to t, tag_path(t) }.join(", ") %>
</p>
<% end %>
</div>
</div>
views/videos/_new.html.erb
<div class="">
<% if current_user == #post.user || current_user.admin %>
<h3>Add video</h3>
<div class="">
<%= form_for [#post, #video] do |f| %>
<div class="">
<%= f.label(:title, "Video Title") %></br >
<%= f.text_field(:title) %>
</div>
<div class="">
<%= f.label(:url, "Video Url") %></br >
<%= f.text_field(:url) %>
</div>
<div class="">
<%= f.label(:tag_list, "Tags (separated by commas)") %></br >
<%= f.text_field(:tag_list, multiple: true) %>
</div>
<div class="">
<%= f.submit("Submit Video") %>
</div>
<% end %>
</div>
<% end %>
</div>
views/videos/show.html.erb
<div class="video-show">
<%= #video.title %>
<%= content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{#video.embed_id}") %>
<p>
Tags: <%= #video.tag_list %>
</p>
<% if current_user == #video.user %>
<%= link_to "Edit Video", edit_video_path(#video) %> |
<%= link_to "Delete Video", video_path(#video), method: :delete, data: { confirm: "Are you sure?" } %> |
<% end %>
<% if current_user == #video.user %>
<%= link_to("Back to Log", post_path(#post)) %> |
<% end %>
<%= link_to("Back to Index", videos_path) %>
</div>
controllers/videos_controller.rb
def index
if params[:tag]
#videos = Video.tagged_with(params[:tag]).page(params[:page]).per_page(10).order(created_at: "desc")
else
#videos = Video.all.page(params[:page]).per_page(10).order(created_at: "desc")
end
end
private
def video_params
params.require(:video).permit(
:title,
:url,
:tag_list,
)
end
I tried to built my search with Ajax and I have added remote: true , and respond_ to block in the controller and I created the partial _xvaziri.html.erb and finally index.js.erb.
But I am not getting the desired results for the Ajax search.
Please refer the images as shown below;
In the above image when I searched for "cash" then I get rendering multiple times in the terminal.
index.html.erb
<% #balance = 0 %>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="table-responsive myTable">
<table class="table listing text-center">
<tr class="tr-head">
<td>Date</td>
<td>Description</td>
<td>Amount</td>
<td>Discount</td>
<td>Paid</td>
<td>Balance</td>
</tr>
<tr>
<td></td>
</tr>
<a href="#" class="toggle-form" style="float: right;" >Search</a>
<div id="sample">
<%= form_tag xvaziris_path, remote: true, method: :get, class: "form-group", role: "search" do %>
<p>
<center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", autofocus: true, class: "form-control-search" %>
<%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>
</p>
<% end %><br>
</div>
<% if #xvaziris.empty? %>
<center><p><em>No results found.</em></p></center>
<% end %>
<%= render #xvaziris %>
</table>
</div>
</div>
</div>
_xvaziri.html.erb
<tr id = "kola" class="tr-<%= cycle('odd', 'even') %>">
<td class="col-1"><%= xvaziri.date.strftime('%d/%m/%Y') %></td>
<td class="col-3"><%= span_with_possibly_red_color xvaziri.description %></td>
<td class="col-1"><%= number_with_precision(xvaziri.amount, :delimiter => ",", :precision => 2) %></td>
<td class="col-1 neg"><%= number_with_precision(xvaziri.discount, :delimiter => ",", :precision => 2) %></td>
<td class="col-1 neg"><%= number_with_precision(xvaziri.paid, :delimiter => ",", :precision => 2) %></td>
<% #balance += xvaziri.amount.to_f - xvaziri.discount.to_f - xvaziri.paid.to_f %>
<% color = #balance >= 0 ? "pos" : "neg" %>
<td class="col-1 <%= color %>"><%= number_with_precision(#balance.abs, :delimiter => ",", :precision => 2) %></td>
</tr>
xvaziris_controller.rb
class XvazirisController < ApplicationController
before_action :set_xvaziri, only: [:show, :edit, :update, :destroy]
def index
#xvaziris = Xvaziri.where (["description LIKE ? OR amount LIKE ? OR paid LIKE ?", "%#{params[:search]}%","%#{params[:search]}%","%#{params[:search]}%"])
respond_to do |format|
format.js
format.html
end
end
def import
Xvaziri.import(params[:file])
redirect_to xvaziris_url, notice: "Xvaziris imported."
end
def show
end
def new
#xvaziri = Xvaziri.new
end
def create
#xvaziri = Xvaziri.new(xvaziri)
if
#xvaziri.save
flash[:notice] = 'Xvaziri Created'
redirect_to #xvaziri
else
render 'new'
end
end
def edit
end
def update
if #xvaziri.update(xvaziri)
flash[:notice] = 'Xvaziri Updated'
redirect_to #xvaziri
else
render 'edit'
end
end
def destroy
#xvaziri.destroy
flash[:notice] = 'Xvaziri was successfully destroyed.'
redirect_to xvaziris_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_xvaziri
#xvaziri = Xvaziri.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def xvaziri
params.require(:xvaziri).permit(:date, :description, :amount, :discount, :paid)
end
end
index.js.erb
<% #balance = 0 %>
<% #xvaziris.each do |xvaziri| %>
$('#kola').append("<%= j render xvaziri %>");
<% end %>
How should I write the above code in order to find searches in xvaziris#index ?
Secondly, I want to display the no results found when search is nil,blank or empty.I wrote the below code but it is not working.
<% if #xvaziris.empty? %>
<center><p><em>No results found.</em></p></center>
<% end %>
Any suggestions are most welcome.
Thank you in advance.
I revised my index.html and index.js.erb as below;
<% #balance = 0 %>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="table-responsive myTable">
<table id = "kola" class="table listing text-center">
<thead>
<tr class="tr-head">
<td>Date</td>
<td>Description</td>
<td>Amount</td>
<td>Discount</td>
<td>Paid</td>
<td>Balance</td>
</tr>
</thead>
<a href="#" class="toggle-formed" style="float: right;" ><strong>Search</strong></a>
<div id="sample">
<%= form_tag xvaziris_path, remote: true, method: :get, class: "form-group", role: "search" do %>
<p>
<center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", autofocus: true, class: "form-control-search" %>
<%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>
</p>
<% end %><br>
</div>
<tbody>
<%= render #xvaziris %>
</tbody>
</table>
</div>
</div>
</div>
index.js.erb
<% #balance = 0 %>
$('#kola tbody').empty();
<% #xvaziris.each do |xvaziri| %>
$('#kola tbody').append("<%= j render xvaziri %>");
<% end %>
I didn't find anything related to my problem.
I have these models:
class Meal < ActiveRecord::Base
has_many :meal_ingredients
has_many :ingredients, through: :meal_ingredients
accepts_nested_attributes_for :ingredients, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :meal_ingredients
end
class Ingredient < ActiveRecord::Base
has_many :meal_ingredients
has_many :meals, through: :meal_ingredients
end
class MealIngredient < ActiveRecord::Base
belongs_to :meal
belongs_to :ingredient
end
In the meal_ingredient model I have a quantity column and I want to let the user set this quantity when creating a new meal with many ingredients. To allow that, I used the cocoon gem. And that's when the problem comes: I must set the ingredient_id and the meal_id to build the association with the quantity but I just hit the database when submiting the "Create Meal" buttom.
Part of the solution I thought is creating a fields_forinside the form and set an instance variable in the controller.
But how can I get these ids? I'm stuck.
class MealsController < ApplicationController
before_action :set_meal, only: [:edit, :update, :show]
autocomplete :ingredients, :name
def index
#meals = Meal.order(updated_at: :desc).paginate(:page => params[:page], :per_page => 4)
end
def show
end
def new
#meal = Meal.new
#qtd = MealIngredient.new
end
def create
#meal = Meal.new(meal_params)
#qtd = #meal.ingredients.map{|r| MealIngredient.new(quantity: params[:quantity], ingredient_id: r.id, meal_id: #meal)}
if #meal.save
flash[:success] = "Refeição criada com sucesso!"
redirect_to meals_path
else
render :new
end
end
def edit
end
def update
if #meal.update(meal_params)
flash[:success] = "Your meal was updated succesfully!"
redirect_to meal_path(#meal)
else
render :edit
end
end
private
def meal_params
params.require(:meal).permit(:name, :picture, ingredients_attributes: [:name, :unit, :carb, :prot, :fat])
end
def set_meal
#meal = Meal.find(params[:id])
end
end
This is what I got so far... I don't think the main problem is being caused by cocoon gem. I think it's about concepts...
The params
Parameters: {"utf8"=>"✓", "authenticity_token"=>"dTYOiz8+pwNfwt432qhy7Yuj0hSVksj0bsTzxp8vD6QaupIJueSO1ASDkwiOB92qCiLO33Ke61aUBGbyvGZJfA==", "meal"=>{"name"=>"tests", "ingredients_attributes"=>{"1449471543091"=>{"name"=>"uva", "unit"=>"und", "carb"=>"1", "prot"=>"1", "fat"=>"1", "_destroy"=>"false"}}}, "meal_ingredient"=>{"quantity"=>"14"}, "commit"=>"Create Meal"}
View
_form.html.erb
<div class = "row">
<div class= "col-md-10 col-md-offset-1">
<%= simple_form_for(#meal) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name %>
</div>
<h3>ingredientes</h3>
<div id="ingredients">
<%= f.simple_fields_for :ingredients do |ingredient| %>
<%= render "ingredient_fields", :f => ingredient %>
<% end %>
</div>
<div class="form-actions">
<div><%= link_to_add_association 'adicionar ingrediente', f, :ingredients, :class => "btn btn-default" %></div>
<div><%= f.button :submit, class: "btn btn-success" %></div>
</div>
<% end %>
</div>
</div>
_ingredient_fields.html.erb
<%= render 'shared/errors', obj: #meal %>
<div class = "nested-fields">
<table class= "table">
<thead>
<tr>
<td>
<%= f.label "Nome" %>
</td>
<td>
<%= f.label "Unidade" %>
</td>
<td>
<%= f.label "Carbo" %>
</td>
<td>
<%= f.label "Prot" %>
</td>
<td>
<%= f.label "Gordura" %>
</td>
<td>
<%= f.label "Quantidade" %>
</td>
<td>
<%= f.label "kcal" %>
</td>
</tr>
</thead>
<tbody>
<tr>
<td scope="row" class="col-md-4">
<%= f.text_field :name, required: true, class: "form-control" %>
</td>
<td class="col-md-2">
<%= f.text_field :unit, required: true, class: "form-control" %>
</td>
<td class="col-md-1">
<%= f.text_field :carb, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
</td>
<td class="col-md-1">
<%= f.text_field :prot, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
</td>
<td class="col-md-1">
<%= f.text_field :fat, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
</td>
<td class="col-md-1">
<%= fields_for #qtd do |f| %>
<%= f.hidden_field :ingredient_id %>
<%= f.number_field :quantity, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
<% end %>
</td>
<td class="col-md-1">
</td>
<td class="col-md-1">
<%= link_to_remove_association "remove item", f, :class => "btn btn-danger" %>
</td>
</tr>
</tbody>
</table>
</div>
Following this tutorial and looking at the cocoon's demo app. It was easy to solve my problem, although I actually don't know exactly what I did here the
<%= link_to_add_association 'adicionar ingrediente', f, :meal_ingredients, 'data-association-insertion-node' => "#ingredients ol", 'data-association-insertion-method' => "append", :wrap_object => Proc.new {|quantity| quantity.build_ingredient; quantity }, :class => "btn btn-default" %>
I hate coding this way but this time I just went with the flow very carefully...
If someone has already used cocoon for that purpose and can explain better I - and the community - would appreciate :D
Changes made:
Model
class MealIngredient < ActiveRecord::Base
belongs_to :meal
belongs_to :ingredient
accepts_nested_attributes_for :ingredient, :reject_if => :all_blank
end
Controller
class MealsController < ApplicationController
before_action :set_meal, only: [:edit, :update, :show]
autocomplete :ingredients, :name
def index
#meals = Meal.order(updated_at: :desc).paginate(:page => params[:page], :per_page => 4)
end
def show
end
def new
#meal = Meal.new
end
def create
#meal = Meal.new(meal_params)
if #meal.save
flash[:success] = "Refeição criada com sucesso!"
redirect_to meals_path
else
render :new
end
end
def edit
end
def update
if #meal.update(meal_params)
flash[:success] = "Your meal was updated succesfully!"
redirect_to meal_path(#meal)
else
render :edit
end
end
private
def meal_params
params.require(:meal).permit(:name, :picture, :tcarb, :tprot, :tfat, :tkcal, meal_ingredients_attributes: [:quantity, ingredient_attributes: [:id, :name, :unit, :carb, :prot, :fat, :_destroy]])
end
def set_meal
#meal = Meal.find(params[:id])
end
end
Views
_form.html.erb
<div class = "row">
<div class= "col-md-10 col-md-offset-1">
<%= simple_form_for(#meal) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name %>
</div>
<h3>ingredientes</h3>
<fieldset id="ingredients">
<ol>
<%= f.fields_for :meal_ingredients do |meal_ingredient| %>
<%= render "meal_ingredient_fields", :f => meal_ingredient %>
<% end %>
</ol>
<div class="form-actions">
<div><%= link_to_add_association 'adicionar ingrediente', f, :meal_ingredients, 'data-association-insertion-node' => "#ingredients ol", 'data-association-insertion-method' => "append", :wrap_object => Proc.new {|quantity| quantity.build_ingredient; quantity }, :class => "btn btn-default" %></div>
</div>
</fieldset>
<div class="form-actions">
<div><%= f.button :submit, class: "btn btn-success" %></div>
</div>
<% end %>
</div>
</div>
_meal_ingredient_fields.html.erb
<div class = "nested-fields">
<table class= "table">
<thead>
<tr>
<td>
<%= f.label "Nome" %>
</td>
<td>
<%= f.label "Unidade" %>
</td>
<td>
<%= f.label "Carbo" %>
</td>
<td>
<%= f.label "Prot" %>
</td>
<td>
<%= f.label "Gordura" %>
</td>
<td>
<%= f.label "Quantidade" %>
</td>
<td>
<%= f.label "kcal" %>
</td>
</tr>
</thead>
<tbody>
<tr>
<%= f.fields_for :ingredient do |fi| %>
<td scope="row" class="col-md-4">
<%= fi.text_field :name, required: true, class: "form-control" %>
</td>
<td class="col-md-2">
<%= fi.text_field :unit, required: true, class: "form-control" %>
</td>
<td class="col-md-1">
<%= fi.text_field :carb, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
</td>
<td class="col-md-1">
<%= fi.text_field :prot, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
</td>
<td class="col-md-1">
<%= fi.text_field :fat, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
</td>
<% end %>
<td class="col-md-1">
<%= f.number_field :quantity, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
</td>
<td class="col-md-1">
</td>
<td class="col-md-1">
<%= link_to_remove_association "remove item", f, :class => "btn btn-danger" %>
</td>
</tr>
</tbody>
</table>
</div>
I used cocoon also, and had some troubles setting it up. I think you have to realiaze that Rails is smarter then you think. You can easily just call save on the parameter string. Just make sure the parameters are all accepted. You will also need :id for ingredients_attributes for instance (and :_destroy, if you allow deletion as well). Oh, and loose the nested_attributes for your join table as well.
I think something like this should work:
def new
#meal = Meal.new
end
def create
#meal = Meal.new(meal_params)
if #meal.save
flash[:success] = "Refeição criada com sucesso!"
redirect_to meals_path
else
render :new
end
end
private
def meal_params
params.require(:meal).permit(:name, :picture, ingredients_attributes: [:id, :name, :unit, :carb, :prot, :fat, :_destroy])
end
If it doensn't, please post your views that contain the main form and the partials.
I'm having a problem with my advanced search.
Essentially, its an advanced search for bands (name, style, bandpicture by checkboxes (checked: have a bandpicture))
Here is the code.
result.html.erb
<table >
<colgroup>
<col width="250" />
</colgroup>
<tr>
<td>
<label for="name">Filter</label></br>
<%= form_tag band_path do %>
<label for="Style">Style</label></br>
<%= select_tag :style_id, options_from_collection_for_select(Style.all, :id, :name, params[:style_id]), include_blank: true, class: "form-control" %>
<br>
</br>
<%= check_box_tag 'options[]', "picture" %>
<%= button_to '#', class: 'btn btn-default' do %>
<%= t(:find) %>
<% end %>
<% end %>
</td>
<td>
<div>
<% #bands.each do |band|%>
<div class="top-bar">
<div class="center">
<div class="info">
<div class="name"><%=band.id %></div>
<div> <%= band.zip %>, <%= band.city %> </div>
</div>
<div class="desc">
<table>
<tr>
<td>Styles</td>
<td>
<% band.styles.each do |s| %>
<%= s.style.name %>
<% end %>
</td>
</tr>
</table>
</div>
<% end %>
</td>
</tr>
</table>
models band.rb
def self.search1(style_id)
Profile.joins("...").where("style_id = ?", style_id)
end
controller.
def searchresult
if params[:style_id].present?
#bands = Band.search1 params[:style_id]
elsif params[:options]
Band.where(:options => #filtered_options)
else
#bands = Band.all
end
end
The searchresult don't show the result of the checkboxes and I have this errors:
undefined method `search1' for #<Class:0x00000008eb5548>
I would like to make show.html.erb(groups) pages open to visitors(,which are not users) as well.
But my code has "if !checklogin? then return end" on groups_controller, so they can't see the show.html.erb pages. I know I should remove "if ! checklogin? then return end" but have no idea how to reconstruct my code as a whole.
Could you give me some hints?
☆members_controller
def checklogin?
if session[:user_id] != nil then
return true
else
redirect_to '/members/login'
return false
end
end
☆login.html.erb(members_controller)
<div class="span4">
<h4 class="title">Users' reading texts</h4>
<% #books.each do |book| %>
<%= image_tag book.imageurl, :width => '30px', :height => '30px'%>
<% end %>
</div><!--span4-->
☆groups_controller
def show
#group = Group.find(params[:id])
#group_message = Group.find(params[:id]).group_messages.build
if !checklogin? then return end
#group_messages = Group.find(params[:id]).group_messages.order("created_at desc")
#me = me?
#member = Member.find(session[:user_id])
#isGr = GroupInMember.where(:member_id => session[:user_id], :group_id =>
params[:id].to_i).count > 0
#gms = Group.find(params[:id]).group_messages.order("created_at desc").scoped
if params[:page].present?
#gms = #gms.where("page = ?" , params[:page] )
end
if params[:content].present?
#gms = #gms.where("content like ?" , "%" + params[:content] + "%")
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: #group_messages }
end
end
☆show.html.erb(groups)
<div class="container-fluid">
<div class="row-fluid">
<div class="span4">
<div id="individual">
<h4>※「<%= #group.name %>」のページ</h4>
<%= link_to image_tag(#group.imageurl, :width=>"100" ,:height=>"150"),#group.detailurl , :target => '_blank' %>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>プロフィール</th>
</tr>
</thead>
<tbody>
<tr>
<th>著者</th>
<td><%= #group.author %></td>
</tr>
<tr>
<th>出版年</th>
<td><%= #group.published %></td>
</tr>
<tr>
<th>出版社</th>
<td><%= #group.publish %></td>
</tr>
<tr>
<th>ページ数</th>
<td><%= #group.page %></td>
</tr>
<tr>
<th>ISBN</th>
<td><%= #group.isbn %></td>
</tr>
</tbody>
</table>
</div><!--individual-->
<%# if #group.admin %>
<%#= link_to 'Profile Edit', edit_group_path(#group),class: "btn btn-midium btn-primary" %>
<%# end %>
<hr>
<% if session[:user_id]%>
<div class="group-side">
<% if #isGr %>
※登録済みです。
<% else %>
※登録していません。
<% end %>
</div>
<p class="group-side">
<%= link_to '本棚登録/解除', {:controller => 'groups', :action => 'join', :id =>
#group.id }, class: "btn btn-midium btn-primary"%></p>
</p>
<p></p>
<div class="group-side2"><b>この本を登録した人一覧:</b></div>
<% #group.group_in_members.each do |m| %>
<% #member = Member.find(m.member_id) %>
<% if #member.provider %>
<%= image_tag #member.image, :width =>'30px', :height =>'30px' %>
<% elsif #member.avatar_file_name %>
<%= image_tag #member.avatar.url(:thumb), :width =>'30px', :height => '30px' %>
<% else %>
<%= image_tag 'love.png', :width =>'30px', :height => '30px' %>
<% end %>
<%# if GroupInMember.where( :member_id => session[:user_id], :group_id => #group.id ).length > 0 %>
<%# end %>
<% end %>
</div>
<% end %>
<div class="span8">
<p>
<b></b>
</p>
<div class="post_on_group">
<% if GroupInMember.where(:member_id =>session[:user_id], :group_id=>#group.id).length > 0 %>
<%= form_for([#group, #group_message]) do |f| %>
<% if #group_message.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#group_message.errors.count, "error") %> prohibited this group_message from being saved:</h2>
<ul>
<% #group_message.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%#= f.label :member_id %>
<%= f.hidden_field :member_id, :value => session[:user_id] %>
</div>
<div class="field">
<%#= f.label :group_id %>
<%= f.hidden_field :group_id %>
</div>
<div class="form_index2">
<%#= f.label :"" %>
<%= f.text_field :page, :class=> "span2" %>ページ(※半角数字の入力必須)
</div>
<div class="form_index4">
<%#= f.label :"何行目あたり?" %>
<%= f.text_field :line, :class=> "span1" %>行目あたり(※半角数字。入力は任意)
</div>
<div class="form_index4">
<%= f.label :"投稿内容(※必須)" %>
<%= f.text_area :content ,:class => "span12",:size => "20x5" %>
</div>
<div class="actions">
<%= f.submit "投稿"%>
</div>
<% end %>
<% end %>
</div> <!--post_on_group-->
<div>
※この本に関する投稿をページ数や投稿内容から検索できます。
</div>
<div class= "form_index">
<%= form_tag({:action=>"show"}, {:method=>"get"}) do %>
<div class="from_field_index5">
<%= text_field_tag 'page' ,'', :class=> "span3" %>
<%= submit_tag 'ページ' %>
<% end %>
</div>
</div>
<div class= "form">
<%= form_tag({:action=>"show"}, {:method=>"get"}) do %>
<div class="from_field_index">
<%= text_field_tag 'content' %>
<%= submit_tag '投稿内容' %>
<% end %>
</div>
</div>
<hr>
<br/>
<% if #gms %>
<% #gms.each do |gm| %>
<div class="message_area">
<div class="each_message">
<%= image_tag gm.group.imageurl,:width => '20', :height => '25' %>
<%= 'Page:' + gm.page.to_s + '&' %><%= 'Line:' + gm.line.to_s %>
<%= gm.member.name %>
(<%= gm.created_at.strftime'%Y-%m-%d %H:%M' %>)
<div class="group_message">
<p class="message_content"><a href="/group_messages/<%= gm.id%>" > <%= truncate(gm.content, { :length => 300}) %></a></p>
</div><!--group_message-->
<br/>
<% if gm.group_message_comments.present? %>
<% gm.group_message_comments.order("created_at asc").each do |gmsc|%>
<div class="group_message_comment">
<p><%= gmsc.member ? gmsc.member.name : "unknown" %> (<%= gmsc.created_at.strftime'%Y-%m-%d %H:%M' %>)</p>
<%= truncate(gmsc.content, { :length => 300}) %>
</div> <!--group_message_comment-->
<br/>
<% end %><!-- each do -- >
<% else %>
<% end %> <!--if -->
</div><!--each_message-->
<br>
</div> <!--message_area-->
<% end %>
<% else %>
<% #group_messages.each do |gm| %>
<div class="message_area">
<div class="each_message">
<%= image_tag gm.group.imageurl,:width => '20', :height => '25' %>
<%= 'Page:' + gm.page.to_s + '&' %><%= 'Line:' + gm.line.to_s %>
<%= gm.member.name %>
(<%= gm.created_at.strftime'%Y-%m-%d %H:%M' %>)
<div class="group_message">
<p class="message_content"><a href="/group_messages/<%= gm.id%>" > <%= truncate(gm.content, { :length => 300}) %></a></p>
</div><!--group_message-->
<br/>
<% if gm.group_message_comments.present? %>
<% gm.group_message_comments.each do |gmsc|%>
<div class="group_message_comment">
<p><%= gmsc.member ? gmsc.member.name : "unknown" %> (<%= gmsc.created_at.strftime'%Y-%m-%d %H:%M' %>)</p>
<%= truncate(gmsc.content, {:length =>300}) %>
</div> <!--group_message_comment-->
<br/>
<% end %><!-- each do -- >
<% else %>
<% end %> <!--if -->
</div><!--each_message-->
<br>
</div> <!--message_area-->
<% end %> <!--each do -->
<% end %>
</div><!--span8-->
The way to check login and redirect, is by using the callback of before_filter
before_filter :check_login
check_login will redirect user to login action unless redirect
def check_login
unless session[:user_id]
flash[:error] = "You must be logged in to access this section"
redirect_to '/members/login'
end
end
If you want to enable access just for some actions - you can exclude them:
before_filter :check_login, :except => [:index, :show, etc..]