ruby/rails displaying database on index view - ruby-on-rails

I've looked at all the other question on here and none seem to fully answer my question, as one solution ends up causeing another error somewhere else in my project.
I am trying to display all "Promotions" from the promotions database on the index view but I keep running into errors, my current error is that in my home controller its saying that "Couldn't find Promotion with 'id'=all".
Any help is greatly appreciated.
Home Controler
class HomeController < ApplicationController
def index
#Promotion = Promotion.find :all
end
Model
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
self.primary_key= :promo_id
end
View
<%= #promotions.promo_id %>

If you want to show all your Promotion, do something like
def index
#promotions = Promotion.all
end
And in your view:
<% #promotions.each do |promotion| %>
<%= promotion.id %>
<%= promotion.name %>
<% end %>

Related

RoR: Using a method defined in user model in a different controller

I'm new in RoR and hoping you experts can help me on this. Apologies in advance if my question sounds weird or stupid. Let me know if you need more clarification, thanks so much in advance.
I have a boolean method called is_pollie (set default to false) in the user model which I want to change it to true once a user completed a form in a different controller called profiles_controller.rb.
Now, I have a user model with a defined method:
class User < ApplicationRecord
has_many :profiles
def self.is_pollie?
is_pollie
end
And in a different controller called profiles_controller.rb:
class ProfilesController < ApplicationController
before_action :authenticate_user!, except: [:show]
def create
#pollie = User.is_pollie?
#profile = current_user.profiles.build(profile_params)
if #profile.save
# what should I put here if I want the is_pollie? to change to true upon
a user click the save button on the form?
redirect_to basic_profile_path(#profile)
else
flash[:alert] = "Oh no, something went wrong."
render :new
end
end
In the page where the form is:
<%= form_for #profile do |f| %>
<div class="form-group">
<label>Displayed name:</label>
<%= f.text_field :display_name,class: "form-control"%>
</div>
<%= f.submit "Save", class: "btn-submit" %>
<% end %>
Hope you understand my question and are able to help. Thanks very much again.
You can try:
current_user.update(is_pollie: true)
BTW, a couple of other points...
This:
class User < ApplicationRecord
has_many :profiles
def self.is_pollie?
is_pollie
end
end
doesn't make any sense because self makes is_pollie? a class method. But, is_pollie is an instance value.
Also, you don't even need is_pollie? because you can use do current_user.is_pollie which will return true of false.
Finally, you're not using #pollie = User.is_pollie? anywhere, so why do it?
Use current_user.update_column(:is_pollie, true)
update method will trigger the call_backs, it's recommended to use update_column for updating a selected attribute.
For multiples you can use update_columns(attributes1: value, attributes2: value)

name error uninitialized constant path in rails

I'm trying to make a form that will post to a database, I'm really struggling at the moment and i'm getting this error.
NameError in AddController#index
uninitialized constant AddController::Newevents
Could you advise what i would need to do?
Heres all the code i have
Form
<%= simple_form_for(#newevent) do |f| %>
<%= f.input :eventname, required: true %>
<%= f.input :eventdate %>
<%= f.input :eventimage %>
<%= f.button :submit %>
<% end %>
controller
class AddController < ApplicationController
def index
#newevent = Newevent.new
end
end
Model
class Newevent < ActiveRecord::Base
def event_params
params.require(:Newevent).permit(:eventname, :eventdate, :eventimage)
end
end
Routes
resources :add
Edit
i now have this error undefined methodnewevents_path'` after changing this
#newevents = Newevent.new
It seems that you miscopied your code here. The error message indicates that your index method actually looks like this
def index
#newevent = Newevents.new
end
Remove the s from the end of Newevent and it should work.
RE: your edit
Your routes declare that you have a resource named add, if you want to show and create your Newevent objects, then you should create a controller for that. Declare resources :newevents in your routes and create a controller to handle it.
You should research RESTful routes, because that's what Rails's resource routing works best with. The form to create a new object should be displayed by the new action and not index.
You should be using create method instead of index if you are using POST http method. index will be called if you are using GET method and it shouldn't be used to post the form data. Refer this link for more information on rails routing.
class AddController < ApplicationController
def create
#newevent = Newevent.new
end
end

Display error from an associatd object Rails

I really don't know the way to display error on a view when we post datas which are associated from another model.
My needs :
I have a form displayed in app/view/libraries/show.html.erb
The comments are associated to library in my app. Means that for a library we can have one or many comments.
In model/comment.rb i put that :
validates :name, presence: true
in app/view/libraries/show.html.erb : i need to display error but don't know the way to retrieve it :
<% if #library.comment.errors.any? %>
<%= #library.comment.errors.count %>
<% end %>
CommentsController
class CommentsController < ApplicationController
def new
end
def create
#library= Library.find(params[:library_id])
#comment = #library.comments.create(params[:comment].permit(:name, :commenter))
redirect_to #library
end
end
This does not work someone can please explain to me the way it works ?? I am doing the guide rails getting start but want to add some features simple in it...
Thanks a lot guys !
If all you need is the count, you can put it in flash
def create
#library= Library.find(params[:library_id])
#comment = #library.comments.create(params[:comment].permit(:name, :commenter))
flash[:error_count] = #comment.errors.count
flash.keep[:error_count]
redirect_to #library
end
<% if flash[:error_count] > 0 %>
<%= flash[:error_count] %>
<% end %>

Polymorphic association gone bad?

I am working on a self-learning project for learning Rails that can be found on github here. (The latest commit includes this error)
However I am posting here all codes:
Model: photo_post.rb
class PhotoPost < ActiveRecord::Base
belongs_to :user
has_attached_file :image, styles: {
post: "200x200>"
}
end
Controller: PostsController
class PostsController < ApplicationController
def show
#post = Post.find(params[:id])
end
end
Controller: PhotoPostsController
class PhotoPostsController < ApplicationController
def create
content = build_content
post = current_user.posts.build(content: content)
if post.save
redirect_to root_path
else
flash.alert = "Please enter a title"
redirect_to root_path
end
end
private
def build_content
PhotoPost.new(photo_post_parameters)
end
def photo_post_parameters
params.require(:photo_post).permit(:image)
end
end
_post.html.erb
<%= div_for post do %>
<%= link_to post.user.username, post.user %>
suggested
<%= render post.content %>
<%= link_to time_ago_in_words(post.created_at), post %>
home_controller.rb
class HomeController < ApplicationController
protect_from_forgery
def show
#title_post = TitlePost.new
#photo_post = PhotoPost.new
#posts = current_user.posts
end
end
I created three models. Posts is the main one and TitlePosts and PhotoPosts are models under Posts.
The Title Posts work fine as I can submit a title.
For Photo Posts I used paperclip. However I try to upload an image I get the following error:
'nil' is not an ActiveModel-compatible object that returns a valid partial path.
You can also check the error on imageshack here.(Screenshot with better_errors).
I was going to copy the relevant codes and files but the full project can be found on github at the link I provided. If you need any further info please ask me.
Thank you.
Any help is greatly appreciated.
In just hitting the page current_user isn't defined, so current_user.posts is trying to get posts on a Nil object.
This cleared up the error, though it isn't going to correct your issues:
HomeController ~ line 7
#posts = []
if current_user
#posts = current_user.posts
end
You may also want to add something to your controller to require authentication so that current_user is set:
before_filter :authenticate_user!
OK this seems weird (to me). The error was caused by forgetting to install ImageMagick.
After installing it everything works fine.

Passing variables in RoR from html to model

I'm new to developing in Ruby on Rails and I'm stuck on a little project that I've been working on to understand RoR better. I am trying to make a little weather website and I'm having trouble sending user input to a model through a controller and to have that model use send back the correct information so that I can parse it and what not. I have not been able so far to send the user param along to the controller so that it will send out the right request. Here is my following code:
hourly.html.erb:
<%= form_tag('/show') do %>
<%= label_tag(:location, "Enter in your city name:") %>
<%= text_field_tag(:location) %>
<br />
<%= submit_tag "Check It Out!", class: 'btn btn-primary' %>
<% end %>
hourly_lookup_controller.rb:
class HourlyLookupController < ApplicationController
def show
#hourly_lookup = HourlyLookup.new(params[:location])
end
end
hourly_lookup.rb:
class HourlyLookup
def fetch_weather
HTTParty.get("http://api.wunderground.com/api/api-key/hourly/q/CA/#{:location}.xml")
end
def initialize
weather_hash = fetch_weather
assign_values(weather_hash)
end
def assign_values(weather_hash)
more code....
end
end
Any help or directions to some good examples or tutorials would be greatly appreciated. Thanks
If you want to send a variable to HourlyLookup, you'll need to do so:
class HourlyLookupController < ApplicationController
def show
#hourly_lookup = HourlyLookup.new(params[:location])
#hourly_lookup.fetch_weather
end
end
class HourlyLookup
attr_reader :location
def initialize(location)
#location = location
end
def fetch_weather
response = HTTParty.get("http://api.wunderground.com/api/cdb75d07a23ad227/hourly/q/CA/#{location}.xml")
parse_response(response)
end
def parse_response(response)
#parse the things
end
end

Resources