Multiple gsub in a loop - ruby-on-rails

I have a small encyclopedia of articles with my Article.rb:
class Article < ActiveRecord::Base
attr_accessible :name, :content
end
I now want to automatically link within the articles if I find text in one article that corrisponds to the name of another article. E.g. in the article named "Example One" the content is "You can also check Example Two for further reading." On save of "Example One" I want to set a link to the article "Example Two". My approach is to add to Article.rb
class Article < ActiveRecord::Base
attr_accessible :name, :content
before_save :createlinks
def createlinks
#allarticles = Article.all
#allarticles.each do |article|
self.content = changelinks(self.content)
end
end
def changelinks(content)
content = content.gsub(/#{article.name}/, "<%= link_to '#{article.name}', article_path(article) %>")
end
My articles_controller is:
def update
#article = Article.find(params[:id])
if #article.update_attributes(params[:article])
redirect_to admin_path
else
render 'edit'
end
end
But obviously there is an error refering to the line content = content.gsub(etc...):
NameError in ArticlesController#update
undefined local variable or method `article' for #
How can I fix this so that it checks all other article names and creates the links for the current article I want to save?

Your changelink method does not "know" what is the article variable. You have to pass it as an argument:
def createlinks
#allarticles = Article.all
#allarticles.each do |article|
self.content = changelinks(self.content, article)
end
end
def changelinks(content, article)
content = content.gsub(/#{article.name}/, "<%= link_to '#{article.name}', article_path(article) %>")
end
But this way to implement links instead of the Articles' name is not the best in my opinion.

Related

I keep getting an undefined method for a class

I've been searching and searching but I cannot find anything to help me with this. I am building an app that allows you to schedule a meeting in a room. The error I'm receiving is
undefined method 'room_id' for #<Room:0x007fa25cc51128>
Here is where the error is occuring in my application.html.erb:
<li><%= link_to "Schedule a Meeting", new_room_meeting_path(#user, #meeting, #room.room_id)%></li>
Here is my meetings controller:
class MeetingsController < ApplicationController
before_action :authenticate_user!
def new
#meeting = Meeting.new
#rooms = Room.all
#room = Room.find(params[:room_id])
end
def index
#meetings = Meeting.all
end
def show
#meeting = Meeting.find(params[:id])
#comments = #meeting.comments
#room = Room.find(params[:id])
end
def create
#user = User.find(params[:user_id])
#meeting = #user.meetings.create(meeting_params)
NotificationMailer.meeting_scheduled(#meeting).deliver_now
if #meeting.save
redirect_to root_path, flash: { notice: "Congratulations!!! Your meeting has been scheduled successfully!!!"}
else
render :new
end
end
private
def meeting_params
params.require(:meeting).permit(:name, :start_time, :end_time, :user_id, :room_id)
end
end
Here is my Meeting model:
require 'twilio-ruby'
class Meeting < ActiveRecord::Base
belongs_to :user
belongs_to :room
has_many :comments
validates_presence_of :user_id, :room_id, :name
def meeting_author_email
user.try(:email)
end
def self.send_reminder_text_message(body, phone)
#account_sid = ENV['twilio_account_sid']
#auth_token = ENV['twilio_auth_token']
#from_phone_number = ENV['twilio_phone_number']
#twilio_client = Twilio::REST::Client.new(#account_sid, #auth_token)
#twilio_client.account.messages.create( to: phone,
from: #from_phone_number,
body: body
)
end
def start_timestamp
(start_time - 6.hours).strftime('%b %e, %l:%M %p')
end
def end_timestamp
(end_time - 6.hours).strftime('%b %e, %l:%M %p')
end
end
The correct URI is: /rooms/:room_id/meetings/new(.:format)
I don't know what the problem is and it is really frustrating me. Any help would be greatly appreciated. I've searched over and over and have been unable to resolve this.
Thanks.
Your Room model doesn't have a column called room_id, but it does have a column called id. Every object in your application has an automatically generated id column as part of the "magic" of Rails. The room_id column that you seem to want belongs to the meetings table, but you indicated that it should come from your room object.
Replace the line:
Schedule a Meeting", new_room_meeting_path(#user, #meeting, #room.room_id)%></li>
with:
Schedule a Meeting", new_room_meeting_path(#user, #meeting, #meeting.room_id)%></li>
Since you stated the URI is "/rooms/:room_id/meetings/new(.:format)", the first part of the fix is to use the :id attribute instead of the: room_id attribute on your #room object, and second to remove the unnecessary objects from your route. You only need the id attribute for a valid URI:
<li><%= "Schedule a Meeting", new_room_meeting_path(#room.id)%></li>
Turns out I was calling the wrong URI.. The correct one was:
<li><%= link_to "Schedule a Meeting", new_user_meeting_path(current_user) %></li>
Is what did the trick. I also made the mistake of not dealing with seed data properly which really threw me for a loop. So once again, THANKS again to all who helped me out. I was working on an old project so I had a lot to go over.

How to pass controller parameters in Ruby on Rails

When I write a message and when pressing the send option,
I want to store student_id, coach_id and message to the database. student_id and coach_id are being saved, but the message field is not being saved. It shows null in the database. How do I fix this?
Any help is appreciated.
Controller file:
class CourseQueriesController <ApplicationController
def index
#course_query = CourseQuery.new
end
def create
# #course_query = CourseQuery.new(course_query_params)
#course_query = CourseQuery.where(student_id: current_student.id, coach_id: "2", message: params[:message]).first_or_create
if #course_query.save
redirect_to course_queries_path, notice: 'Query was successfully send.'
else
render :new
end
end
private
def set_course_query
#course_query = CourseQuery.find(params[:id])
end
# def course_query_params
# params[:course_query].permit(:message)
# end
end
model/course_query.rb:
class CourseQuery < ActiveRecord::Base
belongs_to :student
belongs_to :coach
end
view/course_query/index.html.erb:
<%= simple_form_for (#course_query) do |f| %>
<%= f.button :submit , "Send or press enter"%>
<%= f.input :message %>
<% end %>
database /course_queries:
It seems you didn't permit :course_query.
Try to permit your params the following way:
def course_query_params
params.require(:course_query).permit(:message)
end
But according to the 2nd way you pass params (params[:message]) I think you have a bit different params structure. So try another one:
def course_query_params
params.permit(:message)
end
When you look into the params generated in the log, you will see that the message inside the course_query hash, so params[:message] should be params[:course_query][:message]
#course_query = CourseQuery.where(student_id: current_student.id, coach_id: "2", message: params[:course_query][:message]).first_or_create

Is there a way to send a flash notice through a button_to form in rails?

I currently have the following in my view:
<br><%= button_to "Go on this ride", user_path(#user), method: :get %>
And I want to pass a flash notice through to a view in another controller with this logic:
if #ride.take_ride
flash[:notice] = "Thank you for riding #{#attraction.name}!"
end
Which is based on this logic in my model:
class Ride < ActiveRecord::Base
belongs_to :user
belongs_to :attraction
def take_ride
#user = User.find(user_id)
#attraction = Attraction.find(attraction_id)
can_ride?(#user, #attraction)
end
def can_ride?(user, attraction)
if attraction.tickets > user.tickets && attraction.min_height > user.height
"Sorry. You do not have enough tickets the #{#attraction.name}. You are not tall enough to ride the #{#attraction.name}."
elsif attraction.tickets > user.tickets
enough_tickets?
elsif attraction.min_height > user.height
tall_enough?
else
update_user(user, attraction)
end
end
def tall_enough?
"Sorry. You are not tall enough to ride the #{#attraction.name}."
end
def enough_tickets?
"Sorry. You do not have enough tickets the #{#attraction.name}."
end
def update_user(user, attraction)
user.tickets = user.tickets - attraction.tickets
user.nausea = user.nausea + attraction.nausea_rating
user.happiness = user.happiness + attraction.happiness_rating
user.save
end
end
Is it possible to pass a flash message through my button_to form, and if not, how can I pass this message through?
button_to follows to controller action
and in controller you can set the flash message

Action Mailer problems (beginner)

If I'm entirely honest, I don't understand action mailers in their entirety and I'm finding it hard to discover a learning resource that isn't using an app which is of a completely different context (e.g teamtreehouses todo app). I would really appreciate a little help.
I have a business directory, I want each listings show page to have a form which when filled in, sends the entered info to the listings attached email.
Here's my code:
Mailers/Enquiry.rb
class Enquiry < ActionMailer::Base
default from: "admin#uk-franchise.co.uk"
def lead(listing, info)
#listing = listing
mail(to: #enquiry.email, subject: 'Email Testing Rails App')
mail(to: #listing.leadrecepient, subject: "test")
end
end
listings controller method
def lead
info = params[:leadname]
notifier = Notifier.lead(#listing, info)
end
Routes I'm stuck on configuring as I don't fully understand them for mailers.
What I have in the show listing view so far
<%= form_for lead_path(#leadname, #listing), method: :put do |lead| %>
<% end %>
Again, if anyone could provide me with a learning resource that would accommodate this scenario or a little help I would really appreciate it!
Here's what you have to do:
Do not use mail method twice in one method
class Enquiry < ActionMailer::Base
default from: "admin#uk-franchise.co.uk"
def lead(listing)
#listing = listing
mail(to: #listing.leadrecepient, subject: "test")
end
end
Send your email from within controller action:
class ListingsController
def lead
##listing = Listing...
Enquiry.lead(#listing).deliver
end
end
routes.rb:
# ...
resources :listings do
member do
put :lead
end
end
# ...
view:
<%= form_for lead_listing_path(#listing), method: :put do |listing| %>
<% 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.

Resources