How to access to the company name into an email in rails? - ruby-on-rails

I'm currently trying to use the company name present into an email. But I don't find a simple way to access to. And ask i there is others.
An example is better than explanation :
User.new (mail) => user#company1.com
--> That the value that I want to catch <--
==> #company = company1
if Company.where(name: #company).any?
render show #company
else
reder new Company
end
So if you have any solutions to access to that, you'll be my hero !
Thanks for your time

I'm not an expert on rails, but you can try this :
#pars1 = #company.split('#')
#pars2 = #pars[1].split('.')
#pars3 = #pars[0]
=> company
Try to read that, it can be useful :
How can you return everything after last slash(/) in a Ruby string

Related

Changing Spree from_address

I am trying to change Spree 3.0 from_email
I added this line to my spree initialiser, but it does not work:
Spree::Store.current.mail_from_address = “x#x.com"
Do you know of any reason why not?
I also put it directly in my mailer decorator:
Spree::OrderMailer.class_eval do
def confirm_email_to_store(order, resend = false)
Spree::Store.current.mail_from_address = "x#x.com"
#order = order.respond_to?(:id) ? order : Spree::Order.find(order)
subject = (resend ? "[#{Spree.t(:resend).upcase}] " : '')
subject += "#{'Will Call' if #order.will_call} #{'Just to See' if #order.just_to_see} ##{#order.number}"
mail(to: ENV['STORE_EMAIL'], from: from_address, subject: subject)
end
end
This also did not work
Check you might have created multiple stores via checking Spree::Store.all
Also, spree use current store as store which updated last so you have to check that also
You can simply change the from email address in the Admin Panel under Configuration -> General settings:
Got it to work this way:
Spree::Store.current.update(mail_from_address: ENV["STORE_EMAIL"])
Looking here http://www.davidverhasselt.com/set-attributes-in-activerecord/ you can see that:
user.name = "Rob"
This regular assignment is the most common and easiest to use. It is
the default write accessor generated by Rails. The name attribute will
be marked as dirty and the change will not be sent to the database
yet.
Of course, spree initializers claims to do save in the databse, but it did not:
If a preference is set here it will be stored within the cache & database upon initialization.
Finally calling Spree::Store.current will pull from the database, so any unsaved changes will be lost:
scope :by_url, lambda { |url| where("url like ?", "%#{url}%") }
def self.current(domain = nil)
current_store = domain ? Store.by_url(domain).first : nil
current_store || Store.default
end
Fixing this bug in Spree would be prefrable, this is sort of a workaround

Rails - submitting JSONs to database from controller

I am working on a Rails app, and I am attempting to insert attributes from JSONs as database entries. I'm running into a problem, though, and would appreciate some guidance.
I've been able to jam a few things together and come up with something that sort of works...
def create
#report_group = Array.new
#report_group.push({location:"home", comments:"Hello, database!"}, {location:"away", comments:"Goodbye, database!"})
#report_group.each do |x|
#new_report = Report.new(x)
#new_report.user_id = current_user.id
#new_report.save
end
end
private
def report_params(params)
params.permit(:user_id,:location,:comments)
end
This is a good first step - this commits two entries to my database, one for each of the hashes pushed into #report_group, but it is suffering from a problem - the create action does not reference the report_params whitelist.
I have built several Rails apps where entries are submitted one at a time via the standard Rails form helpers, but I have never done it with multiple JSONs like this before. Trying out the syntax I'd use in a typical form helper situation
#new_report = Report.new(report_params(x))
throws the expectable error undefined method permit' for #<Hash:0x007f966b35e270> but I am not sure what else to do here.
EDIT TO SHOW SOLUTION
Big thanks to #oreoluwa for pointing me in the right direction. Here's the solution that I came up with.
def create
#report_group = Array.new
#report_group.push({location:"home", comments:"Hello, database!"}, {location:"away", comments:"Goodbye, database!"})
#report_group.each do |x|
hash = ActionController::Parameters.new(x)
#new_report = Report.new(report_params(hash))
#new_report.user_id = current_user.id
#new_report.save
end
end
private
def report_params(params)
params.permit(:user_id,:location,:comments)
end
You're getting the error because a Hash is not the same as an ActionController::Parameters. In order to use the permit method with your Hash you may need to first convert it to ActionController::Parameters, as such:
hash = {location:"home", comments:"Hello, database!"}
parameter = ActionController::Parameters.new(hash)
parameter.permit(:user_id,:location,:comments)
I don't know if that is what you're looking for, but I thought to point you in the right direction.

Case statement for STI type column

I have a User model that can have many Websites. For example, I will be able to call User.websites and it will pull up an ActiveRecord array of all of the websites that the User owns. But each website uses Single Table Inheritance (STI) and a type column that will determine the type of the website, like commercial, advertising, or forum. My problem is, that I was to make a case/when statement that runs a function if the the User has a website that is of a certain type. for example:
#user = User.first
case #user.websites
when includes?(Commercial)
'This user has a commercial website'
when includes?(Forum)
'This user has a forum website'
when include?(Ad)
'This user has a advertisement website'
end
Does anyone have a clue on the best way to do such a thing?
Shortest way to do this is using a the map method. Just one line!
#user.websites.select(:type).uniq.map{
|x| puts "This user has a #{x.type.downcase} website"
}
Or if you want to have these strings in an array.
#user.websites.select(:type).uniq.map{|x| x.type.downcase}
If you want to run functions. I would advice naming the functions in a friendly way such as commercial_cost, forum_cost, etc.. so that you can use the send method which makes your code compact.
#user.websites.select(:type).uniq.map{ |x| #user.send(x.type.downcase + "_cost") }
def types
'This user has following websites: ' +
websites.pluck(:type).map(&:downcase).join(', ')
end
#user.rb
def return_data(*types)
types.each do |t|
if Website.where(:user_id => self.id, :type=> t).length>0
send "method_for_owners_of_#{t}_site"
end
end
end
def method_for_owners_of_Commercial_site
end
#...
#user.return_data(["Commercial"])
#user.return_data(["Commercial", "Ad"])
...
According to Rails API
When you do Firm.create(name: "37signals"), this record will be saved
in the companies table with type = “Firm”.

Odd behaviour when extending an object with a module in ruby

If I do the following:
user = User.new
user.extend Customer
user.is_a? Customer == true
it works fine.
However if I do the following (where Profile is a mongoid model and user is embedded):
profile = Profile.all.first
profile.user.extend Customer
profile.user.is_a? Customer == false
user is no longer a customer. There must be a simple reason for this but I can't see it.
Edit: User and Profile are mongoid Models, ie. profile.user.class = User and profile.class = Profile.
My guess: every time you call profile.user you are getting a new object. Try:
2.times{ p profiler.user.object_id }
and see what happens. Then try:
u = profile.user
u.extend Customer
p u.is_a? Customer
p profile.user.is_a? Customer
and see what output you get.
This actually ended up being a bug in Mongoid. Here is the issue with description:
https://github.com/mongoid/mongoid/issues/1933
It is now fixed in the latest commit.

How to store the result of my algorithm?

I have an algorithm that searches through all of my sites users, finding those which share a common property with the user using the algorithm (by going to a certain page). It can find multiple users, each can have multiple shared properties. The algorithm works fine, in terms of finding the matches, but I'm having trouble working out how to store the data so that later I'll be able to use each unit of information. I need to be able to access both the found users, and each of the respective shared properties, so I can't just build a string. This is an example of the output, being run from the perspective of user 1:
user 4
sharedproperty3
sharedproperty6
user 6
sharedproperty6
sharedproperty10
shareproperty11
What do I need to do to be able to store this data, and have access to any bit of it for further manipulation? I was thinking of a hash of a hash, but I can't really wrap my head around it. I'm pretty new to programming, and Ruby in particular. Thanks for reading!
EDIT - Here's the code. I'm fully expecting this to be the most incorrect way to do this, but it's my first try so be gentle :)
So if I'm understanding you guys correctly, instead of adding the interests to a string, I should be creating an array or a hash, adding each interest as I find it, then storing each of these in an array or hash? Thanks so much for the help.
def getMatchedUsers
matched_user_html = nil
combined_properties = nil
online_user_list = User.logged_in.all
shared_interest = false
online_user_list.each do |n| # for every online user
combined_properties = nil
if n.email != current_user.email # that is not the current user
current_user.properties.each do |o| # go through all of the current users properties
n.properties.each do |p| # go through the online users properties
if p.interestname.eql?(o.interestname) # if the online users property matches the current user
shared_interest = true
if combined_properties == nil
combined_properties = o.interestname
else
combined_properties = combined_properties + ", " + o.interestname
end
end
end
if shared_interest == true
matched_user_html = n.actualname + ": " + combined_properties
end
end
end
end
return matched_user_html
render :nothing => true
end
This returns an array of hashes with all users and their corresponding sharedproperties.
class User
def find_matching_users
returning Array.new do |matching_users|
self.logged_in.each do |other_user|
next if current_user == other_user # jump if current_user
# see http://ruby-doc.org/core/classes/Array.html#M002212 for more details on the & opreator
unless (common_properties = current_user.properties & other_user.properties).empty?
matching_users << { :user => other_user, :common_properties => common_properties }
end
end
end
end
end
In your view you can do something like this:
<%- current_user.find_matching_users.each do |matching_user| -%>
<%-# you can acccess the user with matching_user[:user] -%>
<%-# you can acccess the common properties with matching_user[:common_properties] -%>
<%- end -%>
You can use a hash table with the key being the user object and the value being an array of the shared properties . This is assuming that you first need to do a lookup based on the user .
Something like this :
#user_results = { user1 => [sharedproperty3,sharedproperty7] , user2 => [sharedproperty10,sharedproperty11,sharedproperty12]}
You can then acces the values like :
#user_results[user1]
or you can also iterate over all the keys using #user_results.keys

Resources