How to write a rspec for update action in view? - ruby-on-rails

Only User with attribute curator equal true can update homepagelist in article to true and it works fine .
<% if #article.homepagelist%>
<% if current_user.curator %>
<%= form_for #article do|f| %>
<%= f.hidden_field :article_id, :value => #article.id%>
<%= f.hidden_field :title, :value => #article.title%>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :body, :value => #article.body%>
<%= f.hidden_field :image, :value => #article.image%>
<%= f.hidden_field :plain_body, :value => #article.plain_body %>
<%= f.hidden_field :magazine_id, :value => #article.magazine_id%>
<%= f.hidden_field :is_sponsored, :value => #article.is_sponsored%>
<%= f.hidden_field :ad_title, :value => #article.ad_title %>
<%= f.hidden_field :homepagelist, :value => false %>
<%= f.submit "Delete from List" %>
<% end %>
<% end %>
<% else %>
<div class="col-md-2"></div>
<% if current_user.curator %>
<%= form_for #article do|f| %>
<%= f.hidden_field :article_id, :value => #article.id%>
<%= f.hidden_field :title, :value => #article.title%>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :body, :value => #article.body%>
<%= f.hidden_field :image, :value => #article.image%>
<%= f.hidden_field :plain_body, :value => #article.plain_body %>
<%= f.hidden_field :magazine_id, :value => #article.magazine_id%>
<%= f.hidden_field :is_sponsored, :value => #article.is_sponsored%>
<%= f.hidden_field :ad_title, :value => #article.ad_title %>
<%= f.hidden_field :homepagelist, :value => true %>
<%= f.submit "Add List" %>
<% end %>
<% end %>
<% end %>
I want to test the update action after i click on add to list or remove from list that change only the homepagelist variable in article to true when i click add to list and to false when i click on rmove from list
describe 'POST #update/homepagelistvariable' do
it 'allows curator to update homepagelist' do
#user = create(:user)
sign_in #user
#user.curator = true
#article2 = create(:article)
#article2.homepagelist = true
patch :update, article: FactoryGirl.attributes_for(:article,
homepagelist:
#article2.homepagelist)
end
end

describe 'PUT #update/homepagelist' do
it 'curator can add article to homepagelist' do
#user = create(:user, :curator => true)
sign_in #user
#article = create(:article, :user_id => #user.id)
put :update, id: #article.id,
article: FactoryGirl.attributes_for(:article,
homepagelist:
'true')
#article.reload
expect(assigns(:article).homepagelist).to match(true)
end
end
it 'curator can remove article to homepagelist' do
#user = create(:user, :curator => true)
sign_in #user
#article = create(:article, :user_id => #user.id,
:homepagelist => true )
put :update, id: #article.id,
article: FactoryGirl.attributes_for(:article,
homepagelist:
'false')
#article.reload
expect(assigns(:article).homepagelist).to match(false)
end
end

Related

'No implicit conversion of string into integer' with double nested form

Here is my form:
<%= simple_form_for #item do |item_builder| %>
<div class="well">
<%= item_builder.input :name %>
<%= item_builder.input :description, as: :text %>
<%= item_builder.input :tag_list %>
<%= item_builder.simple_fields_for :user_items do |user_item_builder| %>
<%= user_item_builder.input :foo, as: :hidden, input_html: { value: "bar" } %>
<%= user_item_builder.simple_fields_for :user_item_images do |user_item_images_builder| %>
<%= user_item_images_builder.input :picture, as: :file,
input_html: { multiple: true,
name: "item[user_items_attributes][user_item_images_attributes][][picture]" } %>
<% end %>
<% end %>
</div>
<div class="clearfix">
<%= item_builder.submit 'Submit new item request'%>
</div>
<% end %>
and my items_controller
def new
#item = Item.new
#user_item = #item.user_items.build
#user_item.user_item_images.build
end
def create
#item = Item.new item_params
#item.user_items.first.user_id = current_user.id
if #item.save
redirect_to items_path, notice: "Thank you for your item request!"
else
render :new
end
end
def item_params
params.require(:item).permit(:name, :description, :tag_list,
user_items_attributes: [:item_id,
user_item_images_attributes: [:user_item_id, :picture]]).merge(created_by: current_user.id, status: Item::STATUS[:pending])
end
I am getting an error no implicit conversion of String into Integer that points to the first line in my create action. item_params is undefined in the webconsole. Any ideas where my error might be?

TypeError in UsersController#login while move to http://localhost:3000/users/login

I have one error while i am tring to open login page.The errors and all code snippets described below.
Error:
can't convert Symbol into Integer
Extracted source (around line #22):
20 end
21 def login
22 authorized_user = User.authenticate(params [:user][:username],params[:user][:password])
23 if authorized_user
24 session[:user_id] = authorized_user.id
25 flash[:notice] = "Wow Welcome again, you logged in as #{authorized_user.username}"
views/users/index.html.erb:
<h1>This is Registration page..</h1>
<div class="sign">
<%= link_to "Registration", users_new_path ,id: "btn"%>
<%= link_to "Login", users_login_path ,id: "btn1"%>
</div>
views/users/new.html.erb
<h1>Register here</h1>
<div class= "Sign_Form">
<%= form_for #user ,:url => { :action => "create" } do |f|%>
<p>
<%= f.label :NAME %>
<%= f.text_field :name,placeholder:"Enter your name"%>
</p>
<p>
<%= f.label :EMAIL %>
<%= f.text_field :email,placeholder:"Enter your email"%>
</p>
<p>
<%= f.label :PASSWORD %>
<%= f.password_field :password,placeholder:"Enter your password"%>
</p>
<p>
<%= f.submit "SIGN UP"%>
</p>
<% end %>
<% if #user.errors.any? %>
<ul class="Signup_Errors">
<% for message_error in #user.errors.full_messages %>
<li><%= message_error %></li>
<% end %>
</ul>
<% end %>
</div>
views/users/login.html.erb
<h1>Login here</h1>
<div class= "Sign_Form">
<h1>Log in</h1>
<%= form_for #user,:url => { :action => "login" } do |f| %>
<p>
UserName or Email: <%= f.text_field :username,placeholder:"Enter your user name or email" %>
</p>
<p>
Password : <%= f.password_field :password,placeholder:"Enter your valid password"%>
</p>
<p>
<%= f.submit "LOGIN" %>
</p>
<% end %>
</div>
controller/users_controller.rb
class UsersController < ApplicationController
def index
end
def new
#user=User.new
end
def login
end
def create
#user=User.new(user_params)
if #user.save
flash[:notice] = "You Signed up successfully"
flash[:color]= "valid"
redirect_to :action => 'index'
else
flash[:notice] = "Form is invalid"
flash[:color]= "invalid"
redirect_to :action => 'new'
end
end
def login
authorized_user = User.authenticate(params [:user][:username],params[:user][:password])
if authorized_user
session[:user_id] = authorized_user.id
flash[:notice] = "Wow Welcome again, you logged in as #{authorized_user.username}"
redirect_to :action => 'home'
else
flash[:notice] = "Invalid Username or Password"
flash[:color]= "invalid"
redirect_to :action => 'login'
end
end
def home
end
def user_params
params.require(:user).permit(:name, :email,:password)
end
end
model\user.rb
class User < ActiveRecord::Base
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :name, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create
def self.authenticate(username="", password="")
if EMAIL_REGEX.match(username)
user = User.find_by_email(username)
else
user = User.find_by_name(username)
end
if user && user.match_password(password)
return user
else
return false
end
end
end
config/route.rb
Rails.application.routes.draw do
root "users#index"
get "users/new" => "users#new"
get "users/login" => "users#login"
post "users/create" => "users#create"
post "users/login" => "users#login"
get "users/home" => "users#home"
end
users/lauout/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Validation</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<% if flash[:color]== "valid" %>
<div class="valid_notice">
<p><%= flash[:notice]%></p>
</div>
<% elsif flash[:color]== "invalid"%>
<div class="invalid_notice">
<p><%=flash[:notice]%></p>
</div>
<%else%>
<div class="notice">
<p><%=flash[:notice]%></p>
</div>
<%end%>
<%= yield %>
</body>
</html>
Please help me to resolve this error and help also to show the proper validation message(if any wrong found..)
You've got a typo in your code. This:
params [:user][:username]
Should be this:
params[:user][:username]

Build answer with opposite attribute of first answer

My form creates a question and answers. For true and false I currently have one answer being submitted that is the correct answer. I am trying to figure out how to make another answer with the same attributes except have the opposite value, either True or False.
Since the answers are created with the question I'm not sure what to do. I was thinking of the controller having something like, #question.answers.build(question: params[:content]) but am lost. Is there a #question.answers.build.where(content: (#question.content.opposite)) or something? Any help aprreciated
The controller:
def new_tf
#question = Question.new
#question.answers.build
end
def create
#question = Question.new(question_params)
respond_to do |format|
if #question.save
format.html { redirect_to #question, notice: 'Question was successfully created.' }
format.json { render action: 'show', status: :created, location: #question }
else
format.html { render action: 'new' }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
def question_params
params.require(:question).permit(:content, :question_type, :category, :product_id, :active, :user_id, answers_attributes: [ :content, :correct, :question_id ] ).
merge user_id: current_user.id
end
The form:
<h1>New True/False Question</h1>
<%= link_to 'Back', questions_path %>
<%= form_for #question, url: new_tf_question_path(#question) do |f| %>
<%= render 'shared/error_questions' %>
<%= f.label :content, "Question" %><br>
<%= f.text_field :content, class: "input-lg" %>
<%= f.label :category %><br>
<%= f.select :category, [ ["IP Voice Telephony", "ip_voice"], ["IP Video Surveillance", "ip_video_surveillance"], ["IP Video Telephony", "ip_video_telephony"], ["Enterprise Gateways", "enterprise_gateways"], ["Consumer ATAs", "consumer_atas"], ["IP PBX", "ip_pbx"] ], {prompt: "Select Category"}, class: "input-lg" %>
<%= f.label :product_id %><br>
<%= f.collection_select :product_id, Product.all, :id, :name, {prompt: "Select a product"}, {class: "form-control input-lg"} %>
<%= f.label :active %><br>
<%= f.check_box :active %>
<%= f.fields_for :answers do |builder| %>
<%= render 'tf_answers', :f => builder %>
<% end %>
<%= f.select :question_type, [["True False", "TF"]], {class: "form-control input-lg"}, style: "visibility: hidden" %>
<%= f.submit "Create Question", class: "btn btn-lg btn-primary", style: "margin-top: 45px;" %>
<% end %>
The _tf_answers.erb.rb
<%= f.check_box :correct, {checked: true, style: "visibility: hidden"} %>
<%= f.label :content, "Answer" %>
<%= f.text_field :content, :value => 'True', :readonly => true, :class => "input-lg", :id => "answer" %>
<%= button_tag "Toggle True/False", :id => "toggle", :class => "btn btn-small btn-inverse", :type => "button" %>
<script>
function checkAnswer() {
var answer = $('#answer').val();
if ('False' == answer) {
$("#answer").val('True');
} else {
$("#answer").val('False');
}
}
$(document).ready(function(){
$('#toggle').click(function () {
checkAnswer();
});
});
</script>
I ended up creating a new answer after the first one saved.
if #question.save
#answer = Answer.find_by_question_id(#question.id)
if #answer.content == "True"
Answer.create(content: "False", question_id: #answer.question_id, correct: false)
end
if #answer.content == "False"
Answer.create(content: "True", question_id: #answer.question_id, correct: false)
end
Ta-da!
Why doesn't your model automatically create both answers? Extend the save method in your model and you won't have to have this logic in your controller. It probably belongs there anyway.

How to get params value in action on link click

My view code is
<%= form_for(#payment,:url => verify_payment_payment_index_path) do |f| %>
<%= f.radio_button("amount", "10") %>
<%= label :amount, '10 Rs',:style => "display:inline" %> <br>
<%= f.radio_button("amount", "20") %>
<%= label :amount, '20 rs',:style => "display:inline" %><br>
<%= f.radio_button("amount", "50") %>
<%= label :amount, '50 rs',:style => "display:inline" %><br>
<%= f.radio_button :amount, '100' %>
<%= label :amount, '100 rs',:style => "display:inline" %><br>
<%= link_to "Make Payment", verify_payment_payment_index_url,
:class => "btn",
:data => { :toggle => "modal",
"target" => "#myBox" },
"for"=>"Make Payment" %>
<% end %>
And I want to access all values in params in controller action after click on link "Make Payment". So how can I achieve it in rails 3?. Please note that I have to open lightbox on click of link and then submit form
you need to submit the form!
so try the following:
<%= form_for(#payment,:url => verify_payment_payment_index_path) do |f| %>
<%= f.radio_button("amount", "10") %>
<%= label :amount, '10 Rs',:style => "display:inline" %> <br>
<%= f.radio_button("amount", "20") %>
<%= label :amount, '20 rs',:style => "display:inline" %><br>
<%= f.radio_button("amount", "50") %>
<%= label :amount, '50 rs',:style => "display:inline" %><br>
<%= f.radio_button :amount, '100' %>
<%= label :amount, '100 rs',:style => "display:inline" %><br>
<%= f.submit "Make Payment", :class=>"btn",:data => {:toggle => "modal","target"=>"#myBox"},"for"=>"Make Payment" %>
<% end %>

div class wrapping fieldwitherrors won't work

My Rails application just wont add any class to fields with errors. Cant find wihat is the problem.
Got this in model:
validates_presence_of :name
validates_uniqueness_of :name
validates_presence_of :phone
Any ideas where to start looking for solutions ?
This is the view erb file which does not generate the required styled class:
<%= form_for :company, :url => {:action => 'create_lead'}, :html => {:class => "form-horizontal"} do |f| %>
<div class="">
<div class="span2">
<%= f.label :csdd_nr, "CSDD numurs" %>
<%= f.text_field :csdd_nr, {:class => "input-small"} %>
</div>
<div class="span4">
<%= f.label :name, "Nosaukums" %>
<%= f.text_field :name %>
</div>
<div class="span6">
<%= f.label :ap_veh_count, "Auto skaits" %>
<%= f.text_field :ap_veh_count, {:class => "input-small"} %><br /><br />
</div>
<div class="span6">
<%= f.label :office_adress_street, "Faktiskā adrese" %>
<%= f.text_field(:office_adress_street, {:placeholder => 'Iela', :class => "input-medium"}) %> <%= f.text_field(:office_adress_city, {:placeholder => 'Pilsēta', :class => "input-small"}) %> <%= f.text_field(:office_adress_postcode, {:placeholder => 'Pasta indekss', :class => "input-small"}) %>
</div>
<div class="span4">
<%= f.label :web, "Mājaslapa" %>
<%= f.text_field :web %><br /><br />
</div>
<div class="span4">
<%= f.label :phone, "Telefona numurs" %>
<%= f.text_field :phone %>
</div>
<div class="span4">
<%= f.label :email, "E-pasts" %>
<%= f.text_field :email %>
</div>
<div class="span4">
<%= f.label :company_field, "Uzņēmuma nodarbošanās" %>
<%= f.text_field :company_field %><br /><br />
</div>
<%= f.hidden_field(:company_status, :value => "3") %>
<div class="span12">
<br /><br />
<%= submit_tag("Saglabāt", :class => 'btn btn-primary') %>
<%= link_to "Atcelt", {:action => 'list_leads'}, :class => 'btn' %>
</div> def new_lead
#company = Company.new
end
def create_lead
#company = Company.new(params[:company])
if #company.save
flash[:success] = "Uzņēmums saglabāts"
redirect_to(:action => 'new_lead')
else
flash[:alert] = "!!! Uzņēmums nav saglabāts"
redirect_to(:action => 'new_lead')
end
end
</div>
<% end %>
OK, and here is the controller which saves the data to database:
def new_lead
#company = Company.new
end
def create_lead
#company = Company.new(params[:company])
if #company.save
flash[:success] = "Uzņēmums saglabāts"
redirect_to(:action => 'new_lead')
else
flash[:alert] = "!!! Uzņēmums nav saglabāts"
redirect_to(:action => 'new_lead')
end
end
This happens because you're redirecting instead of rendering, when there is a validation error. Your controller should look like:
def create_lead
#company = Company.new(params[:company])
if #company.save
flash[:success] = "Uzņēmums saglabāts"
redirect_to(:action => 'new_lead')
else
flash[:alert] = "!!! Uzņēmums nav saglabāts"
render(:action => 'new_lead')
end
end

Resources