Ruby on Rails SOLR facets between 2 models - ruby-on-rails

In my classifieds app , my "main" model is Classifieds but i have also implemented categorization so Categories has_many :classifieds
Also i have implemented my Categories with awesome_nested_set
And i have Solr search too!
In my sites Classifieds - index.html.erb i render the Classifieds and if search is used i render the corresponding Classifieds.
Now i have implemented a navbar which uses the Category model for navigation.
The navbar shows the Category.roots and the descendants of each root with a dropdown. This leads to the Category - show.html.erb ,where Classifieds are shown according to the Category they are in!
So the question is here:
In my Classifieds - index.html.erb i have successfully implemented Solr facets , which are used as filters but this only works when the user either Searches or just filters in the initial index! So in simple words when he interacts with the Classifieds Controller.
How can i preserve the facet functionality when the user uses the navbar , which means he then interacts with the Category controller
Models:
class Classified < ApplicationRecord
belongs_to :user
belongs_to :category
has_many :photos, dependent: :destroy, inverse_of: :classified
has_many :favorite_classifieds, dependent: :destroy
has_many :favorited_by , through: :favorite_classifieds , source: :user #for the favorite_by to work :source is needed
accepts_nested_attributes_for :photos
searchable do
text :title, :boost => 5
text :model , :created_month , :make , :make_country , :condition ,:treecat,:cat,:price #TO BE CHANGED TO CURRENCY FORMAT
time :created_at
string :treecat
string :price #TO BE CHANGED TO CURRENCY FORMAT
string :created_month
string :cat
string :make_country
string :condition
string :make
string :model
end
def cat
category.root.name
end
def treecat
category.name unless category.name == category.root.name
end
def created_month
created_at.strftime("%B")
end
end
class Category < ApplicationRecord
acts_as_nested_set
has_many :classifieds
end
Classifieds controller index action
def index
#search = Classified.search do
paginate(:page => params[:page] || 1, :per_page => 10)
order_by(:created_at , :desc)
fulltext params[:search]
with(:created_at)
active_model = with(:model ,params[:model]) if params[:model].present?
active_make = with(:make , params[:make]) if params[:make].present?
active_make_country = with(:make_country , params[:make_country]) if params[:make_country].present?
active_condition = with(:condition,params[:condition]) if params[:condition].present?
active_category = with(:cat,params[:cat]) if params[:cat].present?
active_subcategory = with(:treecat,params[:treecat]) if params[:treecat].present?
facet(:model)
facet(:make)
facet(:make_country)
facet(:condition)
facet(:cat , exclude: active_subcategory)
facet(:treecat)
end
#classifieds = #search.results
end
Categories controller show action
def show
#category = Category.find_by_id(params[:id])
end
Classifieds - index.html.erb
<div class="indexbox">
<div class="col-md-2 col-md-offset-1 visible-lg">
<div class="facets">
<h6>Μάρκα</h6>
<ul class="facetlist">
<% for row in #search.facet(:make).rows %>
<li>
<% if params[:make].blank? %>
<%= link_to(row.value, params.merge(:page => 1,:make => row.value).permit!) %> <small class="rowcount"><%= row.count %></small>
<% else %>
<strong><%= row.value %></strong> (<%= link_to "remove", :make => nil %>)
<% end %>
</li>
<% end %>
</ul>
<h6>Χώρα Κατασκευής</h6>
<ul class="facetlist">
<% for row in #search.facet(:make_country).rows %>
<li>
<% if params[:make_country].blank? %>
<%= link_to(row.value, params.merge(:page => 1,:make_country => row.value).permit!) %> <small class="rowcount"><%= row.count %></small>
<% else %>
<strong><%= row.value %></strong> (<%= link_to "remove", :make_country => nil %>)
<% end %>
</li>
<% end %>
</ul>
<h6>Κατάσταση</h6>
<ul class="facetlist">
<% for row in #search.facet(:condition).rows %>
<li>
<% if params[:condition].blank? %>
<%= link_to(row.value, params.merge(:page => 1,:condition => row.value).permit!) %> <small class="rowcount"><%= row.count %></small>
<% else %>
<strong><%= row.value %></strong> (<%= link_to "remove", :condition => nil %>)
<% end %>
</li>
<% end %>
</ul>
<h6>Κατηγορία</h6>
<ul class="facetlist">
<% for row in #search.facet(:cat).rows %>
<li>
<% if params[:cat].blank? %>
<%= link_to(row.value, params.merge(:page => 1,:cat => row.value).permit!) %> <small class="rowcount"><%= row.count %></small>
<% else %>
<strong><%= row.value %></strong> (<%= link_to "remove", :cat => nil %>)
<% end %>
</li>
<% end %>
</ul>
<h6>Κατηγορία</h6>
<ul class="facetlist">
<% for row in #search.facet(:treecat).rows %>
<li>
<% if params[:treecat].blank? %>
<%= link_to(row.value, params.merge(:page => 1,:treecat => row.value).permit!) %> <small class="rowcount"><%= row.count %></small>
<% else %>
<strong><%= row.value %></strong> (<%= link_to "remove", :treecat => nil %>)
<% end %>
</li>
<% end %>
</ul>
</div>
</div>
<% #classifieds.each do |f| %>
<% if !f.sold %>
<div class="center-div" id="index">
<div class="col-lg-12">
<div class="pull-right">
<div class="listingoptions">
<div class="col-md-3">
<p><%= link_to "", new_classified_message_path(:recipient_id => f.user_id , :classified_id => f.id), :class => "glyphicon glyphicon-envelope" , :style => "color:#EFCE7B" %></p>
<%if current_user.favorite_classifieds.collect(&:classified_id).include?(f.id) %>
<p><%= link_to "", favorite_classified_path(f, type: "unfavorite") , :class => "glyphicon glyphicon-heart" , :style => "color:#FF0000", method: :put %></p>
<%else%>
<p><%= link_to "", favorite_classified_path(f, type: "favorite") , :class => "glyphicon glyphicon-heart-empty" , :style => "color:#000000", method: :put %></p>
<%end%>
<p><%= link_to "", editlisting_path(f) , :class => "glyphicon glyphicon-flag" , :style => "color:#EB573B" %></p>
</div>
</div>
</div>
<%= link_to classified_path(f) , :class => "link" do %>
<div class="media">
<div class="mediabox">
<div class="media-left" href="#">
<!-- <img class="media-object" src="..." alt="Generic placeholder image">-->
<% if f.photos.first %>
<%= image_tag f.photos.first.image.url , :class => "media-object"%>
<%end%>
</div>
<div class="media-body">
<h5 class="media-heading"> <%= f.title %></h5>
<small><%= f.created_month %></small>
<% if f.category.parent_id? %>
<small><%= f.category.root.name %></small>
<%end%>
<small><%= f.category.name %></small>
<div class="price ">
<h5><%= f.price %> </h5>
</div>
</div>
</div>
</div>
</div>
</div>
<%end%>
<%end%>
<%end%>
<div class="center-div">
<div class="digg_pagination">
<%= will_paginate #classifieds , :previous_label => '<', :next_label => '>' %>
</div>
</div>
</div>
Categories show.html.erb
<div class="indexbox">
<div class="center-div" id="index">
<div class="categorytitle">
<h4>
<%= #category.root.name %>
<% unless #category.name == #category.root.name %>
<span> >> </span><%= #category.name %>
</h4>
<%end%>
</div>
</div>
<% #category.self_and_descendants.each do |desc| %>
<% desc.classifieds.each do |f|%>
<% if !f.sold %>
<div class="center-div" id="index">
<div class="col-lg-12">
<div class="pull-right">
<div class="listingoptions">
<div class="col-md-3">
<p><%= link_to "", new_classified_message_path(:recipient_id => f.user_id , :classified_id => f.id), :class => "glyphicon glyphicon-envelope" , :style => "color:#EFCE7B" %></p>
<%if current_user.favorite_classifieds.collect(&:classified_id).include?(f.id) %>
<p><%= link_to "", favorite_classified_path(f, type: "unfavorite") , :class => "glyphicon glyphicon-heart" , :style => "color:#FF0000", method: :put %></p>
<%else%>
<p><%= link_to "", favorite_classified_path(f, type: "favorite") , :class => "glyphicon glyphicon-heart-empty" , :style => "color:#000000", method: :put %></p>
<%end%>
<p><%= link_to "", editlisting_path(f) , :class => "glyphicon glyphicon-flag" , :style => "color:#EB573B" %></p>
</div>
</div>
</div>
<%= link_to classified_path(f) , :class => "link" do %>
<div class="media">
<div class="mediabox">
<div class="media-left" href="#">
<!-- <img class="media-object" src="..." alt="Generic placeholder image">-->
<% if f.photos.first %>
<%= image_tag f.photos.first.image.url , :class => "media-object"%>
<%end%>
</div>
<div class="media-body">
<h5 class="media-heading"> <%= f.title %></h5>
<small><%= f.created_month %></small>
<% if f.category.parent_id? %>
<small><%= f.category.root.name %></small>
<%end%>
<small><%= f.category.name %></small>
<div class="price ">
<h5><%= f.price %> </h5>
</div>
</div>
</div>
</div>
</div>
</div>
<%end%>
<%end%>
<%end%>
<%end%>
</div>
im a noob , i know there's stuff wrong with my indentation in html , sorry for that!

Ok i did it by nesting routes and taking some fields from the categories model.
resources :categories do
resources :classifieds do
end
end
Category model:
def nested_classifieds
Classified.where(category_id: self_and_descendants.select(:id))
end
def nested_categories
self_and_descendants
end
Classifieds controller
def index
if #category.present?
#classifieds = #category.nested_classifieds
nested_categories = []
#category.nested_categories.each do |f|
nested_categories << f.id
end
#search = Sunspot.search(Classified ) do
paginate(:page => params[:page] || 1, :per_page => 10)
order_by(:created_at , :desc)
fulltext params[:search]
with(:categoryid,nested_categories)
active_model = with(:model ,params[:model]) if params[:model].present?
active_make = with(:make , params[:make]) if params[:make].present?
active_make_country = with(:make_country , params[:make_country]) if params[:make_country].present?
active_condition = with(:condition,params[:condition]) if params[:condition].present?
active_category = with(:cat,params[:cat]) if params[:cat].present?
active_subcategory = with(:treecat,params[:treecat]) if params[:treecat].present?
active_pricerange = with(:price, params[:price]) if params[:price].present?
fulltext params[:prc]
facet :price
with(:price).less_than(1000)
facet(:model)
#facet(:model , exclude: active_condition)
facet(:make)
facet(:make_country)
facet(:condition)
facet(:cat)
facet(:treecat)
end
#classifieds = #search.results
else
#redirect_to '/'
##classified=#search.results
search
end
end

Related

Rails - Search results are not filtered. Returning all availability

The task scope: A user selects an option from a drop down menu (Single/Double bedroom), clicks on search button and gets all related results. Then on the search page the user can further refine results by using available filters (TV/Shower). For some reason none of these actions modify the search results- the page displays all available listings in the database, rather than the ones that match the criteria..
What am I doing wrong?
Here is what I have so far:
HOME SEARCH BAR
<%= form_tag search_path, method: :get do %>
<div class="row">
<div class="col-md-7">
<%= select_tag :bedroom, options_for_select([['Single', 1], ['Double', 2]]), class: "form-control" %>
</div>
<div class="col-md-2">
<%= submit_tag "Search", class: "btn btn-normal btn-block" %>
</div>
</div>
<% end %>
SEARCH PAGE
<div class="col-sm-3">
<%= search_form_for #search, url: search_path, remote: true do |f| %>
<div class="row">
<div>
<%= check_box_tag "q[is_tv_eq]", true %> TV
</div>
<div>
<%= check_box_tag "q[is_shower_eq]", true %> Shower
</div>
</div>
<div class="row text-center">
<%= f.submit "Search", class: "btn btn-form" %>
</div>
<% end %>
<%= render partial: "rooms/rooms_list", locals: {rooms: #arrRooms} %>
</div>
ROOM LIST PARTIAL
<% rooms.each do |room| %>
<div class="row">
<%= image_tag room.cover_photo(:medium) %>
<%= link_to room.user_id, room %>
<%= room.price %> - <%= room.bedroom %>
<div id="star_<%= room.id %>"></div> <%= pluralize(room.average_rating, "review") %>
</div>
<script>
$('#star_<%= room.id %>').raty({
path: '/assets',
readOnly: true,
score: <%= room.average_rating %>
});
</script>
<% end %>
ROOM MODULE
class CreateRooms < ActiveRecord::Migration[5.0]
def change
create_table :rooms do |t|
t.string :bedroom
t.integer :price
t.boolean :active
t.timestamps
end
end
end
PAGE CONTROLLER
def search
# STEP 1
if params[:search].present? && params[:search].strip != ""
session[:loc_search] = params[:search]
end
# STEP 2
if session[:loc_search] && session[:loc_search] != ""
#rooms_bedroom = Room.where(active: true, bedroom: session[:loc_search]).order(:price)
else
#rooms_bedroom = Room.where(active: true).all
end
# STEP 3
#search = #rooms_bedroom.ransack(params[:q])
#rooms = #search.result
#arRoooms = #rooms.to_a
end
DEFINED THE BEDROOM OPTIONS IN THE ROOM OVERVIEW PAGE (not sure if that helps)
<%= form_for #room do |f| %>
<div class="form-group">
<label> Bedroom Type </label>
<%= f.select :bedroom, [["Single", "Single"], ["Double", "Double"]],
id: "bedroom", prompt: "Select...", class: "form-control" %>
</div>
</div>
<div><%= f.submit "Save", class: "btn btn-normal" %></div>
<% end %>
Thanks

acts-as-taggable-on gem is not persisting tag strings into edit or into show

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

Form button not responding and badly aligned [Refactoring Ruby on Rails]

I'm working on an assignment for a course I'm doing on refactoring some version of the typo blog. I need to add a new form to a page in order to get some information, the problem is that the submit button is not responding and the form is also badly alligned. http://i.imgur.com/5HKMG0L.png
I don't have a good understanding of front-end, so this app is quite confusing for me but this is the way the page is rendered:
**first view that gets called:**
<% #page_heading = _('New article') %>
<%= render "admin/shared/edit", { :form_type => "article", :form_action => { :action => "new", :id => #article.id , :class => ('autosave')} } %>
**admin/shared/edit:**
<% className = form_action.delete(:class) %>
<%= form_tag(form_action, :id => "#{form_type}_form", :enctype => "multipart/form-data", :class => className) do %>
<%= render :partial => "form" %>
<% end %>
[CODE I ADDED TO CREATE A NEW FORM]
***<h3> Merge Articles </h3>
<div class='clearfix'>
<%= form_tag(categories_path, :class => className) do %>
<%= label :article, :merge_with, 'Article ID' %>
<%= text_field :merge_with , '', {:class => 'span1'}%>
<% end %>
<%= submit_tag 'Merge' %>
</div>***
**_form.html.erb:**
<input type="hidden" name="current_editor" id="current_editor" value="<%= current_user.editor %>" />
<input type="hidden" name="user_textfilter" id="user_textfilter" value="<%= current_user.text_filter_name %>" />
<div id="autosave"></div>
<div id="article_keywords_auto_complete" class="auto_complete"></div>
<%= error_messages_for 'article' %>
<div class='editor-right'>
<div class='well'>
<h4><%= _("Publish settings") %></h4>
<div class='actions'>
<%= link_to_destroy_with_profiles(#article) unless #article.id.nil? or #article.state.to_s.downcase == 'draft' %>
<span id='destroy_link'><%= link_to_destroy_draft #article %></span>
<span id='preview_link'><%= link_to(_("Preview"), {:controller => '/articles', :action => 'preview', :id => #article.id}, {:target => 'new', :class => 'btn info'}) if #article.id %></span>
</div>
<div class='clearfix'>
<%= _("Status:") %> <strong><%= #article.state.to_s.downcase %></strong> Change
<ul class='inputs-list'>
<li id='status' style='display: none;'>
<label for="article_published">
<%= check_box 'article', 'published' %>
<%= _("Published") %>
</label>
</li>
</ul>
</div>
<div class='clearfix'>
Comments are <strong>enabled</strong> and trackbacks are <strong>disabled</strong> Change
<ul class='inputs-list' id='conversation' style='display: none'>
<li>
<label for="article_allow_pings">
<%= check_box 'article', 'allow_pings' %>
<%= _("Allow trackbacks") %>
</label>
</li>
<li>
<label for="article_allow_comments">
<%= check_box 'article', 'allow_comments' %>
<%= _("Allow comments") %>
</label>
</li>
</ul>
</div>
<div class='clearfix'>
<%= _("Publish <strong>now</strong>") %> Change
<ul class='inputs-list'>
<li id='publish' style='display: none;'>
<%= calendar_date_select 'article', 'published_at', {:class => 'span3'} %>
</li>
</ul>
</div>
<div class='clearfix'>
<%= _("Visibility:") %> <strong>public</strong> Change
<ul class='inputs-list' id='visibility' style='display: none'>
<li>
<label for="article_password"><%= _("Password:") %>
<%= password_field :article, :password, :class => 'span3' %>
</label>
</li>
</ul>
</div>
<div class='clearfix'>
<%= _("Permalink:") %> Change
<ul class='inputs-list' id='permalink' style='display: none'>
<li>
<%= text_field 'article', 'permalink', {:class => 'span4'} %>
</li>
</ul>
</div>
<div class='clearfix'>
<%= _("Article filter") %>: <strong><%= #article.text_filter.description %></strong> Change
<ul id='text_filter' class='inputs-list' style='display: none'>
<li>
<select name="article[text_filter]" id="text_filter">
<%= options_for_select text_filter_options, #article.text_filter %>
</select>
</li>
</ul>
</div>
<div class='actions'>
<input id='save_draft' type="submit" value="<%= _('Save as draft') %>" name="article[draft]" class='btn info' />
<%= save( _("Publish")) %>
</div>
</div>
<div class='well'>
<h4><%= _("Categories") %></h4>
<%= render 'categories' %>
</div>
<%= get_post_types %>
</div>
<div class='editor-left'>
<div>
<div>
<%= text_field 'article', 'title', :class => 'span1', :style => ' width: 99%', :placeholder => _('Title') %>
</div>
<%= render('images', { :images => #images}) unless #images.empty? %>
<div id='editor-menu'>
<ul class="tabs">
<li id="f" class='<%= "active" if current_user.editor == 'visual' %>'>
<%= build_editor_link("Visual", 'insert_editor', 'fck', 'visual_editor', 'visual') %>
</li>
<li id="s" class='<%= "active" if current_user.editor == 'simple' %> '>
<%= build_editor_link("HTML", 'insert_editor', 'simple', 'simple_editor', 'simple') %>
</li>
</ul>
</div>
<div id="editor">
<div id='quicktags' style='<%= "display: none;" if current_user.editor == 'visual' %>'>
<script type="text/javascript">edToolbar('article_body_and_extended');</script>
</div>
<div id ='visual_editor' <%= "style='display: none;'" if current_user.editor == 'simple'%> >
<%= ckeditor_textarea('article', 'body_and_extended', {:class => 'large', :height => '300px', :rows => '20'}) if current_user.editor == 'visual' %>
</div>
<div id='simple_editor' class='input_text' <%= "style='display: none;'" if current_user.editor == 'visual'%> >
<%= text_area('article', 'body_and_extended', {:class => 'large', :height => '300px', :rows => '20'}) if current_user.editor == 'simple' %>
<%= render_macros(#macros) if current_user.editor == 'simple' %>
</div>
</div>
<h4><%= _("Tags") %></h4>
<div class='class'>
<%= text_field 'article', 'keywords', {:autocomplete => 'off', :style => 'width: 100%'} %>
</div>
<%= auto_complete_field 'article_keywords', { :url => { :action => "auto_complete_for_article_keywords"}, :tokens => ','}%>
</div>
<div class='separator'>
<h4><%= _("Excerpt") %></h4>
<div class=''>
<%= text_area 'article', 'excerpt', {:height => '150', :style => 'width: 100%', :rows => '5'} %>
<span class='help-block'><%=_("Excerpts are posts summaries that are shown on your blog homepage only but won’t appear on the post itself") %></span>
</div>
</div>
<div class=''>
<h4><%= _("Uploads") %></h4>
<p class='help-block'>Uploads will be displayed as attachments in your RSS feed, but won't appear in your articles.</p>
<ul id='attachments' class='inputs-list'>
<%= render 'admin/content/attachment', { :attachment_num => 1, :hidden => false } -%>
</ul>
</div>
</div>
</div>
Any help would be really appreciated. Thanks.
You need to use CSS to align your form to the left. The best way to do this is going into app/assets/articles.css (or any of your CSS files) and adding this line:
.left { text-align: left; }
Then go back into your views and assign anything you want to align to the left the "left" class, for example in your form you can wrap the relevant portions in a div to make everything align left:
<div class="left">
<%= form_tag(categories_path, :class => className) do %>
<%= label :article, :merge_with, 'Article ID' %>
<%= text_field :merge_with , '', {:class => 'span1'}%>
<% end %>
<%= submit_tag 'Merge' %>
</div>

if !checklogin? then return end

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..]

Nested form does not validate association model

I'm using rails 3.2 with active record and sqlserver. I have a problem with nested forms. I have a model registration which has many registration details and each has a person associated.
Here is the model
class Registration < ActiveRecord::Base
set_table_name "dbo.EV_INSCRIPCIONES"
set_primary_key "Id"
belongs_to :category, :foreign_key => 'CategoriaId'
has_many :registrationDetails, :foreign_key => 'InscripcionEventoId'
#has_one :group
accepts_nested_attributes_for :registrationDetails
validates_associated :registrationDetails
validates :Refencia, :presence => true
#validates_presence_of :category_id
attr_accessible :registrationDetails, :category, :Eliminada, :FechaInscripcion, :CreationalDate, :Referencia, :PagoRegistrado, :Acreditado, :registrationDetails_attributes
#after_initialize :init
def init
write_attribute :Eliminada, false
write_attribute :Acreditado, false
write_attribute :PagoRegistrado, false
write_attribute :CreationalDate, DateTime.now
write_attribute :FechaInscripcion, DateTime.now
#write_attribute :Referencia, ''
end
def category_id
self.category.id unless category.nil?
end
def category_id=(id)
self.category = Category.find(id)
end
end
class RegistrationDetail < ActiveRecord::Base
set_table_name "dbo.EV_INSCRIPCION_DETALLE"
set_primary_key "Id"
belongs_to :registration, :foreign_key => 'InscripcionEventoId'
belongs_to :category, :foreign_key => 'CategoriaId'
belongs_to :person, :foreign_key => 'ParticipanteId', :primary_key => 'JUGADOR_ID'
attr_accessible :person, :category, :registration, :Eliminada, :person_attributes
accepts_nested_attributes_for :person
validates_associated :person
after_initialize :init
def init
write_attribute :Eliminada, false
end
end
class Person < ActiveRecord::Base
set_table_name "dbo.PKR_JUGADOR"
set_primary_key "JUGADOR_ID"
has_many :registrationDetails
validates_presence_of :CDNI, :CNOMBRES, :CAPELLIDO, :CSEXO,:CCIUDADRESIDENCIA, :DFECHANACIMIENTO
validates :CDNI, :length => { :minimum => 7, :maximum =>8 }
#validate :validate_birth_date
before_save :set_ids
def set_ids
if id.nil?
_id = Person.maximum(:JUGADOR_ID)
self.JUGADOR_ID = _id +1
write_attribute :CNROJUGADOR, _id+1
end
end
after_initialize :init
def init
write_attribute :TIPODOCUMENTO_ID, 1 if read_attribute(:TIPODOCUMENTO_ID).nil?
end
def full_name
self.surname + ", " + self.name
end
protected
def validate_birth_date
errors.add(:birth_date, 'must be a valid datetime') if ((Date.strptime(birth_date, "%d/%m/%Y") rescue ArgumentError) == ArgumentError)
end
end
My view
index.html.erb
<h1><%= t '.title', :name => #event.CNOMBRETORNEO %> </h1>
<%= render 'form_nested' %>
_form_nested
<%= form_for #registration, :url => {:controller => "registration", :action => "save"}, :html => {:class=> 'form-horizontal'} do |f| %>
<legend><%= t '.legend' %></legend>
<% if f.object.errors.any?%>
<div id="error_explanation">
<h3 class="text-error"><%= t '.has-errors' %></h3>
</div>
<% end %>
<input type="hidden" id="event_date" name="event_date" value="<%= #event.DDIAACTIVIDAD.strftime('%Y%m%d') %>" />
<input type="hidden" id="event_id" name="event_id" value="<%= #event.TORNEOPOKER_ID %>" />
<%= f.fields_for :registrationDetails do |d| %>
<%= render 'details_fields' , :f => d %>
<% end %>
<% has_error = f.object.errors.has_key? :category %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :category, :class=> 'control-label' %>
<div class="controls">
<%= f.hidden_field :category_id %>
<div class="btn-group" data-toggle-name="presenter_category_id" data-toggle="buttons-radio">
<%#categorias.each do |x| %>
<button value="<%= x.Id %>" type="button" class="btn" data-age-from="<%= x.FromAge %>" data-age-to="<%= x.ToAge %>"><%= x.Name %></button>
<%end %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:category].join(", ")%></span>
<% end %>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary"><%= t '.save' %></button>
</div>
<%end%>
_detatails_fields
<%= f.object.errors.inspect %>
<%= f.fields_for :person do |p| %>
<%= render 'person_fields', :f => p %>
<% end %>
_person_fields
<%= f.hidden_field :id %>
<% has_error = f.object.errors.has_key? :CDNI %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CDNI, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-book"></i></span>
<%= f.text_field :CDNI, :class => 'input' %>
<div class="add-on" id="document_loader"><%= image_tag '6-0.gif' %></div>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CDNI].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :DFECHANACIMIENTO %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :DFECHANACIMIENTO, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-calendar"></i></span>
<%= f.text_field :DFECHANACIMIENTO, :class=>'input' %>
<span id="person_age" class="add-on"></span>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:DFECHANACIMIENTO].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :CNOMBRES %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CNOMBRES, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-user"></i></span>
<%= f.text_field :CNOMBRES,:class=>'input' %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CNOMBRES].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :CAPELLIDO %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CAPELLIDO, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-user"></i></span>
<%= f.text_field :CAPELLIDO,:class=>'input' %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CAPELLIDO].join(", ")%></span>
<% end %>
</div>
</div>
<div class="control-group">
<%= f.label :CTELEFONO, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-certificate"></i></span>
<%= f.text_field :CTELEFONO,:class=>'input' %>
</div>
</div>
</div>
<% has_error = f.object.errors.has_key? :CSEXO %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CSEXO, :class=> 'control-label' %>
<div class="controls">
<%= f.hidden_field :CSEXO %>
<div class="btn-group" data-toggle-name="presenter_sex" data-toggle="buttons-radio">
<button type="button" class="btn" value="M"><%= t '.masculine' %></button>
<button type="button" class="btn" value="F"><%= t '.femenine' %></button>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CSEXO].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :CCIUDADRESIDENCIA %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CCIUDADRESIDENCIA, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-map-marker"></i></span>
<%= f.text_field :CCIUDADRESIDENCIA,:class=>'input' %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CCIUDADRESIDENCIA].join(", ")%></span>
<% end %>
</div>
</div>
And finally the controller
class RegistrationController < ApplicationController
def index
date = "20120729"
id = 1
#id = params[:event_id] unless params[:event_id].nil?
#date = params[:event_date] unless params[:event_date].nil?
#event = Event.find(date,id)
#groups = Group.all
#categorias = Category.where("DiaActividad = ? and TorneoId = ?", date, id)
#registration = Registration.new
#registration.registrationDetails.build( :person => Person.new)
end
def save
#registration = Registration.new(params[:registration])
if #registration.save
redirect_to :controller => 'home'
else
date = params[:event_date]
id = params[:event_id]
#event = Event.find(date,id)
#groups = Group.all
#categorias = Category.where("DiaActividad = ? and TorneoId = ?", date, id)
render :action => 'index'
end
end
end
What is happening? well first of all, the changes on any field are not saved, and the validations are not displayed. When i submit the form, it returns to the same page, and seems the form has errors but no one is displayed, and the data is lost.
Hope you can help me.
Thanks in advance
Well, I don´t Know why but I solved using resources.
In my routes.rb file
resources :registrations
Before I have something like this.
match 'registration/(:event_date)/(:event_id)' => 'registration#index'
match 'registration/save' => 'registration#save'
I think the problem was my custom routes. But i really don`t know.

Resources