Display error from an associatd object Rails - ruby-on-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 %>

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)

ruby/rails displaying database on index view

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 %>

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

Trying to link to specfic new comic review page

I'm trying to get a link on an articles show page so that when a user clicks write new review it takes them to the link
/comic_reviews/'the article they want to comment on'/reviews/new
where they will be directed to the new reviews page
how can i accomplish this with
In your routes file you would specify a route like this
match '/comic_reviews/:comic_name/reviews/new' => 'reviews#new', via: :get
Then in your reviews controller you would need something like this
reviews_controller.rb
class ReviewsController < ApplicationController
def new
#comic = Commic.find_by_name(params[:comic_name])
if #comic
#review = #comic.reviews.build
render 'new'
else
#Render some error page since comic was not found
end
end
end
You will then have access to #comic and #review in your reviews/new view so you could build a form that just makes a post to create a review and allows you to store it. This should get you going.
Edit
In your new view you'd need to have a form that looks something like this
<%= form_for #review do |f| %>
<%= f.label :some_attribute %>:
<%= f.text_field :some_attribute %><br />
<%= f.submit %>
<% end %>
This will be expecting you have a route to create a review in your routes file and an action in your ReviewsController.
If you are struggling with such topics I suggest you read over this excellent tutorial
http://ruby.railstutorial.org/ruby-on-rails-tutorial-book
Or just read through the documentation for Rails API which will give you pretty accurate examples.
You can do this via routes
resources :comic_reviews do
resources :reviews
#probably_some_other_route_here
end
And with restful pattern it will be easy to achieve whatever you want
controller
Someclass < Someotherclass
#some your code
def new
#instance_var = Your_model.new
end
def create
#instance_var = Your_model.new(params[:some_name_here])
if #instance_var.save
redirect_to somewhere
else
render 'new'
end
end
end
Also you'll need form, but i dont think that will cause any troubles

Resources