Why one method work perfectly for one action and do not work for another? - ruby

I'm newbee in rails, so could you explain why method survey_type works for this (attempts/new):
<h2 class="survey-title">
<%= #survey.name %>
<p><small><%= #attempt.survey.description %></small></p>
</h2>
<%= form_for(#attempt, url: attempt_scope(#attempt)) do |f| %>
<%= hidden_field_tag :survey_id, #survey.id %>
<ol class="questions">
<% if is_multanswer?(#survey.survey_type) %>
<%= f.fields_for :answers, get_answer_fields(#attempt) do |answer_fields| %>
<li>
<% question = answer_fields.object.question %>
<p class="question"><%= question.text %></p>
<ul class="options">
<%= collection_check_boxes('survey_attempt[answers_attributes]', question.id, question.options, :id, :text) do |b| %>
<li class="checkbox">
<%= b.label { b.check_box + b.text } %>
</li>
<% end %>
</ul>
</li>
<% end -%>
<% else %>
<%= f.fields_for :answers, get_answer_fields(#attempt) do |answer_fields| %>
<li>
<% question = answer_fields.object.question %>
<p class="question"><%= question.text %></p>
<ul class="options">
<%= collection_radio_buttons('survey_attempt[answers_attributes]', question.id, question.options, :id, :text) do |b| %>
<li class="radio">
<%= b.label { b.radio_button + b.text } %>
</li>
<% end %>
</ul>
</li>
<% end -%>
<% end %>
</ol>
<%= f.submit "Submit", class: 'btn btn-default' %>
<% end -%>
and do not work for this (attempts/show):
<div class="container">
<h2 class="survey-title">
<%= #attempt.survey.name %>
<p><small><%= #attempt.survey.description %></small></p>
</h2>
<ol class="questions">
<% if is_multanswer?(#survey.survey_type) %>
<% #attempt.answers.each do |answer| %>
<li>
<p class="question"> <%= answer.question.text %> </p>
<ul class="options">
<% answer.question.options.each do |option| %>
<li class="checkbox">
<label>
<%= check_box_tag '', '', the_chosen_one?(answer, option), disabled: true %>
<% color = get_color_of_option(answer, option) %>
<span class="<%= color %> <%= the_chosen_one?(answer, option) %>"> <%= option.text %> <%= get_weight(option) %> </span>
</label>
<p class="answers-number"> <%= number_of_people_who_also_answered(option.id) %> </p>
</li>
<% end %>
</ul>
</li>
<% end %>
<% else %>
<% #attempt.answers.each do |answer| %>
<li>
<p class="question"> <%= answer.question.text %> </p>
<ul class="options">
<% answer.question.options.each do |option| %>
<li class="radio">
<label>
<%= radio_button_tag '', '', the_chosen_one?(answer, option), disabled: true %>
<% color = get_color_of_option(answer, option) %>
<span class="<%= color %> <%= the_chosen_one?(answer, option) %>"> <%= option.text %> <%= get_weight(option) %> </span>
</label>
<p class="answers-number"> <%= number_of_people_who_also_answered(option.id) %> </p>
</li>
<% end %>
</ul>
</li>
<% end %>
<% end %>
here is controllers:
attempts_controller
class AttemptsController < ApplicationController
helper 'surveys'
before_filter :load_survey, only: [:new, :create]
def index
#surveys = Survey::Survey.active
end
def show
#attempt = Survey::Attempt.find_by(id: params[:id])
render :access_error if current_user.id != #attempt.participant_id
end
def new
#participant = current_user
unless #survey.nil?
#attempt = #survey.attempts.new
#attempt.answers.build
end
end
def create
#attempt = #survey.attempts.new(params_whitelist)
#attempt.participant = current_user
if #attempt.valid? && #attempt.save
correct_options_text = #survey.correct_options.present? ? 'Bellow are the correct answers marked in green' : ''
redirect_to attempt_path(#attempt.id), notice: "Thank you for answering #{#survey.name}! #{correct_options_text}"
else
build_flash(#attempt)
#participant = current_user
render :new
end
end
def delete_user_attempts
Survey::Attempt.where(participant_id: params[:user_id], survey_id: params[:survey_id]).destroy_all
redirect_to new_attempt_path(survey_id: params[:survey_id])
end
private
def load_survey
#survey = Survey::Survey.find_by(id: params[:survey_id])
end
def params_whitelist
if params[:survey_attempt]
params[:survey_attempt][:answers_attributes] = params[:survey_attempt][:answers_attributes].map { |attrs| { question_id: attrs.first, option_id: attrs.last } }
params.require(:survey_attempt).permit(Survey::Attempt::AccessibleAttributes)
end
end
def current_user
view_context.current_user
end
end
and surveys_controller:
class SurveysController < ApplicationController
before_filter :load_survey, only: [:show, :edit, :update, :destroy]
def index
type = view_context.get_survey_type(params[:type])
query = if type then Survey::Survey.where(survey_type: type) else Survey::Survey end
#surveys = query.order(created_at: :desc).page(params[:page]).per(15)
end
def new
#survey = Survey::Survey.new(survey_type: view_context.get_survey_type(params[:type]))
end
def create
#survey = Survey::Survey.new(params_whitelist)
if #survey.valid? && #survey.save
default_redirect
else
build_flash(#survey)
render :new
end
end
def edit
end
def show
end
def update
if #survey.update_attributes(params_whitelist)
default_redirect
else
build_flash(#survey)
render :edit
end
end
def destroy
#survey.destroy
default_redirect
end
private
def default_redirect
redirect_to surveys_path, notice: I18n.t("surveys_controller.#{action_name}")
end
def load_survey
#survey = Survey::Survey.find(params[:id])
end
def params_whitelist
params.require(:survey_survey).permit(Survey::Survey::AccessibleAttributes << :survey_type)
end
end
and helpers:
def get_color_of_option answer, option
if is_quiz?(answer.question.survey.survey_type)
if option.correct
'bg-success'
elsif the_chosen_one?(answer, option)
'bg-danger'
end
elsif is_score?(answer.question.survey.survey_type)
get_weight_html_class option
end
end
def get_survey_type survey_type
get_survey_types[survey_type] || get_survey_types.invert[survey_type]
end
def get_survey_types
{ 0 => 'quiz',
1 => 'score',
2 => 'poll',
3 => 'multanswer'
}
end
def is_quiz? something
something == 0 || something == 'quiz'
end
def is_score? something
something == 1 || something == 'score'
end
def is_poll? something
something == 2 || something == 'poll'
end
def is_multanswer? something
something == 3 || something == 'multanswer'
end
Thanks in advance!

In your AttemptsController you have
before_filter :load_survey, only: [:new, :create]
that sets the #survey variable for your new action, but doesn't get called for show, so that action never gets the variable set.
You can add :show into your :only conditions
before_filter :load_survey, only: [:new, :create, :show]
and that should fix things

Related

How would I get all people, that are following my in Ruby

I am using the act_as_follower gem, and I get all the users, that I follow, but now I want all the users, that are following me, how would I do that. I checked and I think something like this
current_user.followers, but I cant get it working. My code for people that I am following is this:
<% #users = User.all %>
<% #users.each do |user| %>
<% unless user == current_user %>
<div class="container people-lists list-following">
<%= image_tag("/assets/" + user.avatar + ".png", alt: "Logo", class: "people-image") %>
<%= user.username %>
<% if user_signed_in? %>
<% unless user == current_user %>
<% if current_user.following?(user) %>
<%= button_to("Un-Follow", user_follow_path(user.to_param, current_user.get_follow(user).id), :method => :delete, :remote => true, class: 'btn btn-primary button') %>
<% else %>
<%= button_to("Follow", user_follows_path(user.to_param), :remote => true, class: 'btn btn-primary button') %>
<% end %>
<% end %>
<% end %>
</div>
<% end %>
<% end %>
I found I the User.all returns all of them, and I can use the all_following, and follows like this and it works.
<% #users = current_user.all_following %>
And like this
<% #users = current_user.followers %>

Display data according to text field value using Rails 3

I have a issue.I want to fetch data from data base according to text field value.This text field will take two types of value.First one is simple number(e.g-123456789) and second one is like this(e.g-123456789/1).The simple number is present in DB for one table.In the second one number after "/" (i.e-1) is another table's id which is associated with first table.Then my aim is when user will give the input "123456789" the data will fetch according to this number by searching and when user will give the input "123456789/1" first it will split the number and values will be fetched according to both number and id (i.e-123456789 and 1) from the both table.
Here i am explaining some of my code below.
homes/hcsy_html.erb
<% if current_admin %>
<div class="header">
<div class="navbar-header">Swargadwar, Puri Municipality,govt of odisha</div>
<div class="nav navbar-top-links navbar-right">
<div class="image"></div>
</div>
<div class="name-div">
</div>
</div>
<div class="menu-div">
<div id="leftsidebtn">
<ul>
<li>Create User</li>
<li>Scan Report</li>
<li>View and Payment Report
<ul>
<li>HCSY</li>
</ul>
</li>
<li>Payment Validate</li>
<li>Log Out</li>
</ul>
</div>
</div>
<div class="content-div">
Logged in as:<%= current_admin.email %>
<center><h1>HARICHANDRA SAHAYATA YOJANA SLIP</h1></center>
<%= form_for :hcsy,:url => {:action =>'scan_hcsy' } do |f| %>
<%= f.text_field :reciept,placeholder:"Get your scan code",:onchange => 'this.form.submit();' %>
<% end %>
<% if params[:id] %>
<center><h1>HARICHANDRA SAHAYATA YOJANA SLIP</h1></center>
Receipt No :<%= #hcsys.Receipt_No %>
<div class="left-content">
<p>Deceased Name :</p> <%= #hcsys.Deceased_Name %>
<p>Beneficary name :</p> <%= #hcsys.Beneficiary_Name %>
<p>Relation with Deceased :</p> <%= #hcsys.Beneficiary_Rel_With_Decease %>
<p>Address :</p> <%= #hcsys.Address %>
<p>Police station :</p> <%= #hcsys.PoliceStation %>
<p>Mobile No :</p> <%= #hcsys.Mobile_No %>
<p>Occupation :</p> <%= #hcsys.Occupation %>
<p>Brahmin :</p> <%= #hcsys.Brahmin %>
<p>Amount Required :</p> <%= #hcsys.Amount_Required %>
<p>Has He/She recieved any assistance erlier from this fund :</p> <%= #hcsys.Recieved_Fund_Earlier %>
</div>
<div class="right-content">
<p>BPL :</p> <%= #hcsys.BPL %>
<p>Govt. Service :</p> <%= #hcsys.Govt_Service %>
<p>Business :</p> <%= #hcsys.Business %>
<p>Land of property :</p> <%= #hcsys.Land_Property %>
<p>Other :</p> <%= #hcsys.Others %>
</div>
<% end %>
</div>
<% end %>
controller/homes_controller.rb
class HomesController < ApplicationController
def index
end
def registration
#user=User.new
end
def usersave
#admin=Admin.find(params[:id])
#user=User.new(params[:user])
#user.admin_id=#admin.id
if #user.save
flash[:notice]="User has created successfully"
flash[:color]="valid"
redirect_to :action => "index"
else
flash[:alert]="User could not created"
flash[:color]="invalid"
render 'registration'
end
end
def hcsy_reg
#hcsy=THcsy.new
end
def create_reg
#hcsy=THcsy.new(params[:hcsy])
if #hcsy.save
flash[:notice]="Data has saved successfully"
flash[:color]="valid"
redirect_to :action => "hcsy_details",:id1 => params[:id],:id2 => #hcsy.id
else
flash[:alert]="Data could not saved successfully"
flash[:color]="invalid"
render 'hcsy_reg'
end
end
def scan_hcsy
#hcsy=THcsy.find_by_Receipt_No(params[:hcsy][:reciept])
if #hcsy
flash[:notice]="Check the record"
flash[:color]="valid"
redirect_to :action => 'hcsy',:id => #hcsy.id
else
flash[:alert]="Receipt number could not found"
flash[:color]="invalid"
render 'hcsy'
end
end
def hcsy
if params[:id]
#hcsys=THcsy.find(params[:id])
end
end
def scanrecord
#hcsy=THcsy.find(params[:id])
end
def hcsy_deatils
#t_hcsy=THcsyFundTypeMaster.new
end
def create_details
#t_hcsy=THcsyFundTypeMaster.new(params[:t_hcsy])
if #t_hcsy.save
flash[:notice]="Check the record"
flash[:color]="valid"
redirect_to :action => 'hcsy_details_master',:id1 => params[:id1] ,:id2 => params[:id2] , :id3 => #t_hcsy.HCSY_Fund_Type_ID
else
flash[:alert]="Receipt number could not found"
flash[:color]="invalid"
render 'hcsy_deatils'
end
end
def hcsy_details_master
#t_hcsy_master=THcsyDetails.new
end
def create_details1
#admin=Admin.find(params[:id1])
#hcsy=THcsy.find(params[:id2])
#t_hcsy=THcsyFundTypeMaster.find_by_HCSY_Fund_Type_ID(params[:id3])
#t_hcsy_master=THcsyDetails.new(params[:t_hcsy_master])
#t_hcsy_master.Created_By=#admin.id
#t_hcsy_master.HCSY_ID=#hcsy.id
#t_hcsy_master.HCSY_Fund_Type_ID=#t_hcsy.HCSY_Fund_Type_ID
if #t_hcsy_master.save
flash[:notice]="Record has created"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="Record could not create"
flash[:color]="invalid"
render 'hcsy_details_master'
end
end
end
Here i have done for simple number please help me to fetch data from both table by the second input number(i.e-123456789/1).For this all operations are executing inside "scan_hcsy" method.Atleast help me to split the number(i.e-123456789/1) to 123456789 and 1 so that i can fetch data according to this number and id.
You can split the string, which results into an Array:
"12345678/1".split('/')
=> ["12345678", "1"]
In your case:
splitted = params[:hcsy][:reciept].split('/')
hcys = splitted[0]
table_id = splitted[1]

How to access hidden_field in controller in Ruby on rails

Question: How to access hidden field value post_id from file view/comments/_comment.html.erb and use it in controllers/dashboards_controller.rb?
- there are 2 controllers - dashboard and comments, and using gem act_as_commentable_with_threading
Now I get: ActiveRecord::RecordNotFound in DashboardsController#index Couldn't find Post without an ID
config/routes.rb
resources :comments, :only => [:create, :destroy]
controllers/dashboards_controller.rb
class DashboardsController < ApplicationController
def index
#post = Post.new
#user = current_user
#newest_users = User.newest_players
#feed_posts = Post.paginate(:page => params[:page], :per_page => 8)
#last_clubs = Club.last_clubs
#commented_post = Post.find(params[:post_id])
# trying to access params from view/comments/_comment.html.erb
# comments is another controller...
# do other operations with #commented_post
#comments = #commented_post.comment_threads.order('created_at desc')
#new_comment = Comment.build_from(#commented_post, current_user, '')
end
end
view/comments/_comment.html.erb
Add comment
place for a comment form
<div class="comment-form">
<%= form_for :comment, :remote => true do |f| %>
<%=f.hidden_field 'post_id', post.id %>
# need to use this value in dasboard controller
<%=f.text_field :body %>
<% end %>
</div>
view/dashboards/_feed_post.html.erb
<ul class="post-items">
<%if #feed_posts.any? %>
<% #feed_posts.each do |post| %>
<li>
<span class="image"><%= image_tag post.image.url(:message) if post.image?%></span>
<span class="content"><%= post.text_html %></span>
<span class="tags">Tags:<%= post.tag_list %></span>
<span class="meta">
Posted <%= time_ago_in_words(post.created_at) %> ago.
| <%= post.user.full_name %>
</span>
<%= render 'comments/form' ,:locals => { :comment => #new_comment, :post_id => post.id } %>
<%= render 'comments/comment', :collection => #comments, :as => :comment, :post_id => post.id %>
</li>
<% end %>
<% end %>
</ul>
view/dashboards/index
<div class="row">
<div class="span7">
<!--form for creating a new post-->
<section>
<%= render :template => 'posts/new' %>
</section>
<!--dashboard feed_post-->
<section>
<%= render :partial => 'dashboards/feed_post' %>
</section>
</div>
you are using f.hidden_field so you will get
<%=f.hidden_field 'post_id', post.id %>
will create following html ref hidden_field
<input type="hidden" id="comment_post_id" name="comment[post_id]" value="#{comment.post_id}" />
so you can access this as following in your controller
params[:comment][:post_id]
so use following instead
#commented_post = Post.find(params[:comment][:post_id])
if you want 'post_id' in params[:post_id] use hidden_field_tag like following
<%= hidden_field_tag 'post_id', post.id %>

Do I need an Enumerator for this?

I want to do this:
<div class="menu">
<%- render_menu do |title,path,children| %>
<%= link_to title, path %>
<div class="submenu">
<%= render_menu(children) do |title,path,children| %>
<%= link_to title, path %>
<%= children %>
<%- end %>
</div>
<% end %>
</div>
The method render_menu would look something like this:
def render_menu(children=nil)
children = Paths.roots if children.nil?
children.collect do |child|
[ child.title, child.path, child.children ]
end
end
I'm not sure what the render_menu needs to return to get the three params..
The render_menu will grab the default menu items if no argument is given..
You have to use yield and replace each for collect inside render_menu:
def render_menu(children=nil)
children = Paths.roots if children.nil?
children.each do |child|
yield([child.title, child.path, child.children])
end
end
You should also modify your template to not display the value returned by render_menu:
<div class="submenu">
<% render_menu(children) do |title,path,children| %>
<%= link_to title, path %>
<%= children %>
<% end %>
</div>

Object in hidden_field_tag becomes nil when partial is called into an index (yet, works in individual Show view)

Rails 3.1.3
I am making a simple site where people can share short stories and can rate those stories on a 5 Star rating system. The Star rating system is the problem. I can get it to work fine in the stories/show.html view, but not on the indexed home page. Here is my code:
home.html.erb
<% content_for(:scripts) do %>
<%= javascript_include_tag 'rating_ballot'%>
<% end %>
<div id="talesFeedHome">
<p class="notice"><%= notice %></p>
<%= render #tales.sort_by { |tale| tale.created_at }.reverse %>
</div>
<p class="clear"> </p>
tales/_tale.html.erb
<% if signed_in? %>
<div id="homeTales">
<ul>
<div id="taleShow">
<div id="controlPanel">
<li id="taleUserName"><%= tale.user.name %></li>
<li id="averageRating"> Your Rating:<br /><%= render "tales/stars" %></li>
</div>
<div id="taleDisplay">
<li><%= link_to(tale) do %>
<span><%= tale.title %> </span>
<span><%= tale.content %></span>
<% end %>
</li> <br />
</div>
</div>
</ul>
</div>
<% else %>
...
tales/_stars.html.erb
<div id="starRating">
<%= form_for(rating_ballot, :remote => true, :html => { :class => 'rating_ballot' }) do |f| %>
<%= f.label("value_1", content_tag(:span, '1'), {:class=>"rating", :id=>"1"}) %>
<%= radio_button_tag("rating[value]", 1, current_user_rating == 1, :class => 'rating_button') %>
<%= f.label("value_2", content_tag(:span, '2'), {:class=>"rating", :id=>"2"}) %>
<%= radio_button_tag("rating[value]", 2, current_user_rating == 2, :class => 'rating_button') %>
<%= f.label("value_3", content_tag(:span, '3'), {:class=>"rating", :id=>"3"}) %>
<%= radio_button_tag("rating[value]", 3, current_user_rating == 3, :class => 'rating_button') %>
<%= f.label("value_4", content_tag(:span, '4'), {:class=>"rating", :id=>"4"}) %>
<%= radio_button_tag("rating[value]", 4, current_user_rating == 4, :class => 'rating_button') %>
<%= f.label("value_5", content_tag(:span, '5'), {:class=>"rating", :id=>"5"}) %>
<%= radio_button_tag("rating[value]", 5, current_user_rating == 5, :class => 'rating_button') %>
<%= hidden_field_tag(:tale_id, #tale.id) %>
<% end %>
</div>
It is at this point, in the hidden field tag, that I get this error:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
Here are the 3 relevant controllers:
pages_controller.rb
class PagesController < ApplicationController
def home
#tales = Tale.all
end
end
tales_controller.rb
class TalesController < ApplicationController
respond_to :html, :js
def new
#tale = Tale.new
end
def show
#tale = Tale.find(params[:id])
end
def index
#tales = Tale.all
#tale = Tale.find(params[:id])
end
...
ratings_controller.rb
class RatingsController < ApplicationController
before_filter :authenticate_user!
respond_to :html, :js
def create
#tale = Tale.find_by_id(params[:tale_id])
#rating = Rating.new(params[:rating])
#rating.tale_id = #tale.id
#rating.user_id = current_user.id
if #rating.save
respond_to do |format|
format.html { redirect_to #tale, :notice => "Your rating has been saved" }
format.js
end
end
end
def update
#rating = current_user.ratings.find_by_tale_id(params[:tale_id])
#tale = #rating.tale
if #tale and #rating.update_attributes(params[:rating])
respond_to do |format|
format.html { redirect_to #tale, :notice => "Your rating has been updated" }
format.js
end
end
end
end
The problem is here somewhere. Somehow when rendering #tales on the home page, this invalidates the #tale.id on the _stars partial. I can not figure out how to solve this. Thank You.
ok, I think your value of #tales is nil so please do the following things and let me know what would be the result
first put raise #tales.Inspect in your home method in your PagesController
second <%= raise tale.inspect%> in _tale.html.erb.
want to check weather value of tale is null or not.

Resources