So I tried to add this code to first the views and then the controller. It didn't work and gave me an error : undefined method save for 4:Fixnum.
Code:
<% unless location.user.interests.blank? %>
<% #merged_array = location.user.interests.split(',').uniq +
current_user.interests.split(',').uniq %>
<% location.score = #merged_array.length - #merged_array.uniq.length %>
<% location.score.save %>
<% else %>
<% location.score = 0 %>
<% location.score.save %>
<% end %>
But then I removed it from both controller and views..... Now the index page isn't showing the locations at all I checked and the show page is working and records still exist
This is really not the way it should work.
Just read a bit about the MVC pattern - it's worth it!
You shouldn't check in production credentials into your repository - especially not if it is public.
Checkout https://github.com/bkeepers/dotenv to keep your keys and passwords privately.
You should change your passwords immediately!
The error you got is because location.score is an integer not an object - location.save! will save the object with its new score.
PS: You don't want to be the guy who let production creds into the guide for new employees. https://www.reddit.com/r/cscareerquestions/comments/6ez8ag/accidentally_destroyed_production_database_on/
Beside of that, Keep going!
Sorry forgot that it only displays locations within a 50 mile radius and i was travelling...... Silly me :)
Related
I am struggling with a college project course, and I have been stuck with this error for weeks now, despite the suggestions provided by colleagues and tutors.
In my create method for a given table. I am trying to have the page containing the forms for new record entries redirect back to the index page after saving. Instead, I get redirected to this error instead, highlighting #courier=Courier.new(courier_new_path) with the error stating that it is not a hash, and would not redirect me back into index. However, when manually searching the index, I see that the data string would indeed get updated.
I have tried renaming the path label, but Rubymine prompt suggestions appear limited, and any further deviation would cause a different error
The following is the create method in the controller page (courier_controller.rb):
def create
#courier=Courier.new(params.require(:courier).permit(:courier_name,:courier_email))
#courier.save
redirect_to courier_path(#courier)
#courier=Courier.new(courier_new_path)
if #courier.save
redirect_to(:controller=>'courier' ,:action=>'index')
else
render('new')
end
end
Here is the code for the form page (courier/new/html.erb):
<h1>Courier#new</h1>
<p>Find me in app/views/courier/new.html.erb</p>
<%= form_with scope: :courier, :url => {:action => 'create'}, local: true do |f| %>
<p>
<%= f.label :courier_name %><br/>
<%= f.text_field :courier_name %>
</p>
<p>
<%= f.label :courier_email %><br/>
<%= f.text_field :courier_email %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
I have tried renaming #courier as Courier.new(courier_create_path) or Courier.nww(courier_path), I have tried looking for arguments using a hash form, but none seemed equivocal nor translatable as a solution to my problem.
Any suggestions would help. This is part of a college project, and as a multimedia student not as savvy in programming compared to fellow peers, I would highly appreciate suggestions that I can try out.
Many thanks in advance.
Has anyone tried to explain what is actually going on in your create method? I've added comments after each line to say what that line is doing.
def create
#courier=Courier.new(params.require(:courier).permit(:courier_name,:courier_email))
# use the params to build a new courier record (the permit part is usually in a separate method that other methods can access but it works this way)
#courier.save
# Save the new courier record to the database
redirect_to courier_path(#courier)
# Send the user back to the "show" page of the courier record (not index!)
#courier=Courier.new(courier_new_path)
# this makes no sense, you are trying to create a new courier object using a path method
# Basically you are saying: #courier = Courier.new('/courier/new')
if #courier.save
#you are trying to save this record that will fail because you can't create a courier by passing it a url
redirect_to(:controller=>'courier' ,:action=>'index')
#send the user to the index page of the courier views.
else
render('new')
#something went wrong so go back to the new courier form.
end
end
When your program gets to line 4 redirect_to courier_path(#courier) it is going to exit the create method and send the user to http://my_app:3000/couriers/1 where the number 1 would be the ID in the database of the record you just created. This would relate to the file in your app in app/views/couriers/show.html.erb. It sounds like you want to get to http://my_app:3000/couriers which presents the user with the file app/views/couriers/index.html.erb Not sure why you are doing anything after that line.
Also it is unclear what error you are getting. You need to look at your webserver console, the place where you run "rails s" that shows all the communications between the browser and your app. find the stack trace that starts with the actual error, and add that to your question above (don't paste it in a comment, it will be too long and impossible to read).
I think you just need:
def create
#courier=Courier.new(params.require(:courier).permit(:courier_name,:courier_email))
if #courier.save
redirect_to #courier #if you want to redirect to their 'show" page
else
render('new')
#something went wrong so go back to the new courier form.
end
end
What might be confusing to a new programmer is that Rails is doing so much "magic" behind the scenes it gets very confusing if you don't already know the underlying concepts happening behind the scenes. You are saying redirect_to(:controller=>'courier' ,:action=>'index') which specifically says "go to the index page of the couriers" but you can say redirect_to #courier and it will assume that you want to go to the page that shows the record of the courier you just created. If you really want to go the table that shows all of the couriers you would replace that with redirect_to :couriers The symbol :couriers tells it to go to the index method of the couriers controller.
I had a model named b_page I wanted to create another column , so I ran a migration:
rails g migration add_status_to_b_page status:string
so migration was successful. Users should be able to update their status so I put this on the _form.html.erb:
<div class="field">
<%= f.label :status %><br>
<%= f.text_field :status %>
</div>
was successful but then i added it to the show.html.erb
<%= #b_page.status %>
but everytime i make a new b_page or edit the current one I dont see it on show.html.erb
Without seeing your code I guess you have to whitelist the new parameter (status) in your BPageController (at the very bottom, in something like def bh_pages_params).
You can check the logs whether the parameter that comes into your controller (via the form) actually arrives at the data (ActiveRecord Model), this whitelisting approach (called Strong Parameters) is in place to safe guard your data.
thx I fixed my problem I forgot to add status in
params.require(:b_page).permit(:Bpage_name, :banner_img, :profile_img, :status) in my controller
I've been struggling for a while on this (been reading a lot of the ruby on rail guides to try and understand this), but I'm not sure how user inputs work.
I am trying to search for a restaurant in my database with a list of fields the user specifies (cuisine, zipcode, review score). I have created a html.erb page that has the options for all of these.
Here is my controller.
class WelcomeController < ApplicationController
def home
#my_search = Restaurant.joins(:inspection).where(cuisine: c, zipcode: z, totalscore: 1..h)
end
My models for restaurant and inspection also have relations between them (the foreign keys).
How would you go about letting the user give inputs for c (cuisine), z (zipcode) and 1..h (score range)?
I know that people have answered this question in the past, but I think I need a concrete example to actually understand how to do this. As in, what would you put in the html.erb code so that when an option is selected, that value is passed to the method?
Thank you
First you need to create a form in the view. The simplest way to do this is with form_tag:
<%= form_tag(home_path) do %>
<%= text_field_tag 'cuisine' %>
...other inputs
<% end %>
Next, make sure you have a route defined for your controller action in config/routes.rb
post 'home' => 'welcome#home'
Most likely your routes will look different but this is the bare minimum you need.
And in your controller you can access the submitted data using the params object
class WelcomeController < ApplicationController
def home
#restaurants = Restaurant.joins(:inspection).where(
cuisine: params[:cuisine],
# ...other params
)
end
end
I have a checkout button on my product page show view which accepts the offer. Each offer belongs_to a user. I don't want the user who created the offer to be able to accept it themselves so if it is the current user on the page I want to hide the button. I can't figure out why this code doesn't work:
<% unless current_user.id == #offer.sender_id %> #sender_id is a foreign key in the offer model that makes each offer belong_to a user.
<div id="accept_offer">
<%= button_to 'Accept Offer', etc %>
</div>
<% end %>
current_user is a devise gem method I believe.
Any help appreciated.
your code seems correct, you maybe need to look into your Offer.sender_id attribute in the model to see if it contains the right user id (of the creator of the offer). You could check that by creating a new offer throught your application (in the browser) then, in the console you type:
Offer.last.sender_id
And check if it corresponds to your current_user id
Just saw the error and got the reason.
You tried the page without sign in so unless current_user works, this means you have not signed in. Your original code doesn't considered this case.
Generally you should see an error as current_user is not defined but you may have disabled that.
Two ways to fix:
Change current_user, assign an object in any case
class ApplicationController
def current_user
super || User.new
end
end
Change the logic
<% if current_user && current_user != #obj.sender %>
# Button code
# Only signed in user with different id can see it
I have a rails app. Homepage searches the movies database and displays the results in the results page for the search query.
Now, in the results page there are a list of movies (say 5) and the results page displays the attributes of the movies in the left side bar.
For example,
=================Movies results page================
Left-side-bar
Genres
Comedy(link_to)
Horror(link_to)
Languages
English(link_to)
German(link_to)
Results set
1 Anger management
2 American pie
3 Evil dead
4 Grudge
5 Du riescht so gut
=====================================================
Now, after the first search, my search controller has a #movieid array which has those 5 movieids(mentioned above). And the left-side-bar has the filters to filter this further.
Using the #movieid array i listed the movies in the results set.
If i click on the link "comedy", I want the results page to show only "1. Anger management" and "2. american pie".
If i click on the link "german". It should only display "5. Du riescht so gut". Thats it.
Right now,
Im confused of the following options,
1. Im thinking of passing the genre_id and #movieid array through the link_to as parameters.
2. Use cookie[:store] to save the #movieid array
3. Store the #movieids in database and retrieve.
I dont know how to handle this. Remember my #movieid array can contain 100000 ids as well.
Help me with the best practice and performance.
Thanks!
Edit:
Can i use Mysql Views to store the result set? problem is what happens if a 100000 users are searching at the same time, that many views will be created?, is it ok?. What is the good practice?
I think, I did great!
Answering to my question:
From first main search page, if I run a search query, on the movies table and get 300 records as a result from 5000 movies in the table then I dynamically create a view in the mysql database from rails method, AR::Base.connection.execute() which holds the movie_ids of the 300 searched movies.
Now moving on, in the second page if the user filters 300 results based on language or genre, I narrow down my search, doing a search on the created view and not the MOVIES table again. This is done by getting the language_id and genre_id from the url after passing it to a link_to helper.
I get a session_id from every browser and append an alphabet in front of that id which will be used as my view name.
If the user visits the home page or gets past the search page and finds the exact product, I will drop my view and i will keep a timeout to drop my view say 1 hour and every day I will drop the views created the day before.
I heard from Ryan that persisting an User search is a good practice. I was interested in that as well. Now I think I have implemented it. Please hit me with all the negatives in my approach, Im trying to run a company here.
Thanks!
Edit:
Forgot my gratitude to Ashitaka.
Of course I have added will_paginate gem. Its working alright.
TIP: In will_paginate, if you are listing out 83 movies with :per_page => 10, then you wont be able to display the total number of movies in the first page of 9 pages(10+10+....+3). If you wish to do it like Movies(83). Then, #movies.total_entries.to_s helps.
Thanks to you too!
Since you can have 100000 different movies, you need to implement pagination in your rails app. This is made easy with the will_paginate gem. Here's an example:
# movies_controller.rb
def index
#movies = Movie.search(params[:q]).order('name').paginate(:page => params[:page], :per_page => 15)
respond_to do |format|
format.html
end
end
And then in your view:
# index.html.erb
<%= form_tag movies_path, :method => 'get' do %>
<div>
<%= text_field_tag :q, params[:q] %>
<%= submit_tag "Search", :name => nil %>
</div>
<% end %>
<table>
<tr>
<th>Movies</th>
</tr>
<% #movies.each do |movie| %>
<tr>
<td><%= link_to movie.name, movie %></td>
</tr>
<% end %>
</table>
<%= will_paginate #movies %>
Searching and filtering is definitely a thorny issue. It's really hard to explain in detail such a complicated thing, so I will simply point out to the incredible Railscast that explains how to do what you want.
http://railscasts.com/episodes/240-search-sort-paginate-with-ajax