Error 404 when i use ActiveResource with Redmine - redmine

i have a problem with redmine. In fact, i've created a model who use ActiveResource :
require 'active_resource'
class New < ActiveResource::Base
#self.site = "http://localhost:3000/"
#self.format = :xml
#self.user = 'admin'
#self.password = 'admin'
class << self
attr_accessor :api_key
end
def save
prefix_options[:api_key] = self.class.api_key
super
end
end
New.site = 'http://localhost:3000'
New.api_key = '471bea6d1c4452b82b57287a281ff04392ae4118'
nw = New.new(:field_1 => 'value 1')
nw.save
# Retrieving news
news = New.find(:all)
puts news.first.title
#Retrieving an new
new = New.find(1)
puts new.description
puts new.author.name
# Creating an new
new = New.new(
:project_id => 1,
:author_id => 1,
:title => 'Annonce',
:summary => 'Annonce',
:description => 'Annonce'
)
if new.save
puts new.id
else
puts new.errors.full_messages
end
# Updating an 'new'
new = New.find(1)
new.title = 'NEW INFO '
new.save
# Deleting an new
new = New.find(1)
new.destroy
I'v an error 404 and i don't understand why:
/Users/bj/.rvm/gems/ruby-1.9.3-p429/gems/activeresource-4.0.0/lib/active_resource/connection.rb:144:in `handle_response': Failed. Response code =404. Response message = Not Found . (ActiveResource::ResourceNotFound)
PS: If i use api key or if i use self.site i've a 404 too !
Can you help me please? I tried many things but no every things doesn't works. Thanks for your answers !

The basic problem seems to be, that Redmine is not responding the way ActiveResource expects it. This could be due to changes in Rails 3, that where not properly reflected in Redmine yet.
The best option for you would maybe be dropping ActiveResource for something like httparty. You should also known, that Redmine currently only supports fetching all news (/news.json) and all news within a project (/projects/test_project/news.json). Neither fetching a single news directly nor creating or updating news is supported via the REST API.
Edit: The actual cause for the 404 in your code is due to the fact, that ActiveResource tried to POST to /news.json which is - as I have mentioned above - not supported by the REST API. If you remove the save call, you will run into another issue, where ActiveResource is not able to deserialize the response in New.find(:all). This lead me to think, that Redmine and ActiveResource are currently incompatible. Also the demo code in the Redmine wiki to create an issue, does not work for me.

Related

In Rails4, using Trailblazer, how do I access the current_user

We are building a Rails4 app using Trailblazer. I have never worked with Trailblazer before and I am confused about how to do things.
We are building an auction site. I was previously using a traditional controller, and this route endpoint was working fine:
def bill
#profile = Profile.find_by user_id: current_user_id
#current_order = Order.order(created_at: :desc).find_by(user_id: current_user_id)
#batch = #current_order.batch
if #batch.nil?
puts "There was no batch linked to the current order of #{#current_order.id}"
flash[:error] = "We are sorry, but we could not determine which batch your order belongs to."
else
#price_shown_to_customer = #batch.price + ENV["FUELBID_FEE_PER_GALLON"].to_f
#amount = #current_order.quantity * #price_shown_to_customer
end
But now I'm suppose to create this as a Trailblazer api, using a Representer class.
So in routes.rb I added something for "charges":
namespace :api do
get '/price' => 'info#info'
post '/order' => 'orders#create'
get '/charges' => 'charges#bill'
end
I created this Api but copying-and-pasting another:
module Api
class ChargesController < ApiApplicationController
respond_to :json
def bill
respond_with OpenStruct.new.extend(ChargesRepresenter)
end
end
end
I tested the above with a simple Representer and it all worked fine, so everything is good up to this point. If I return simple data from the Representer, then I can see it fine here:
http://localhost:3000/api/charges.json
But I need to get the current_user. How is this done? Right now, this does not work:
module ChargesRepresenter
include Roar::JSON
collection :price_shown_to_customer
def price_shown_to_customer
current_order = Order.order(created_at: :desc).find_by(user_id: current_user_id)
puts "current_order"
puts current_order.id
batch = current_order.batch
batch.price + ENV["FUELBID_FEE_PER_GALLON"].to_f
end
end
current_user_id exists in my traditional controllers because we set up Devise and so my traditional controllers inherit it:
class ChargesController < SecuredController
But is there any way to get it in a Trailblazer Representer?
Hope this answer is not too late.
If you can switch to Decorator pattern instead of a Module.
Representer really doesn't need to know and doesn't care if it is called from controller or console or test. All it needs is a hash to build your json object from. So you can just pass another attribute called current_user_id to your Representer and then use it inside r presenter like you do.
FYI:
If you need a more immediate response you can also copy your question to https://gitter.im/trailblazer/chat . There are usually several people hanging out there. But it's also good to post a question here for posterity.

Rails 4 Action Mailer Previews and Factory Girl issues

I've been running into quite an annoying issue when dealing with Rails 4 action mailer previews and factory girl. Here's an example of some of my code:
class TransactionMailerPreview < ActionMailer::Preview
def purchase_receipt
account = FactoryGirl.build_stubbed(:account)
user = account.owner
transaction = FactoryGirl.build_stubbed(:transaction, account: account, user: user)
TransactionMailer.purchase_receipt(transaction)
end
end
This could really be any action mailer preview. Lets say I get something wrong (happens every time), and there's an error. I fix the error and refresh the page. Every time this happens I get a:
"ArgumentError in Rails::MailersController#preview
A copy of User has been removed from the module tree but is still active!"
Then my only way out is to restart my server.
Am I missing something here? Any clue as to what is causing this and how it could be avoided? I've restarted my server 100 times over the past week because of this.
EDIT: It may actually be happening any time I edit my code and refresh the preview?
This answers my question:
https://stackoverflow.com/a/29710188/2202674
I used approach #3: Just put a :: in front of the offending module.
Though this is not exactly an answer (but perhaps a clue), I've had this problem too.
Do your factories cause any records to actually be persisted?
I ended up using Factory.build where I could, and stubbing out everything else with private methods and OpenStructs to be sure all objects were being created fresh on every reload, and nothing was persisting to be reloaded.
I'm wondering if what FactoryGirl.build_stubbed uses to trick the system into thinking the objects are persisted are causing the system to try and reload them (after they are gone).
Here's a snippet of what is working for me:
class SiteMailerPreview < ActionMailer::Preview
def add_comment_to_page
page = FactoryGirl.build :page, id: 30, site: cool_site
user = FactoryGirl.build :user
comment = FactoryGirl.build :comment, commentable: page, user: user
SiteMailer.comment_added(comment)
end
private
# this works across reloads where `Factory.build :site` would throw the error:
# A copy of Site has been removed from the module tree but is still active!
def cool_site
site = FactoryGirl.build :site, name: 'Super cool site'
def site.users
user = OpenStruct.new(email: 'recipient#example.com')
def user.settings(sym)
OpenStruct.new(comments: true)
end
[user]
end
site
end
end
Though I am not totally satisfied with this approach, I don't get those errors anymore.
I would be interested to hear if anyone else has a better solution.

Rails4 Deprecation Warning

Rails4 is getting depreciation warning when I am upgrading from rails 3.2 to rails 4.0. I have this query.
Child.find(:all, :include => :children_users, :conditions => "state = 'active' AND owner_id = #{self.id} AND children_users.user_id = #{other_user.id}")
I am getting deprecation warning as follow :-
DEPRECATION WARNING: It looks like you are eager loading table(s) (one of: splits, accounts) that are referenced in a string SQL snippet. For example:
Post.includes(:comments).where("comments.title = 'foo'")
Currently, Active Record recognizes the table in the string, and knows to JOIN the comments table to the query, rather than loading comments in a separate query. However, doing this without writing a full-blown SQL parser is inherently flawed. Since we don't want to write an SQL parser, we are removing this functionality. From now on, you must explicitly tell Active Record when you are referencing a table from a string:
Post.includes(:comments).where("comments.title = 'foo'").references(:comments)
If you don't rely on implicit join references you can disable the feature entirely by setting `config.active_record.disable_implicit_join_references = true`. (called from splits_under_100_percent at /Users/newimac/RailsApp/bank/app/models/user.rb:274)
To solve this problem, I have try like this
Child.includes(:children_users).where(state: active, owner_id: self.id, children_users.user_id = other_user.id).load
or
Child.where{(state: active, owner_id: self.id, children_users.user_id = other_user.id).includes(:children_users)}
But none of them work.
children_users.user_id = other_user.id wrong.
The correct one is: "children_users.user_id" => other_user.id
Thank You for #Zakwan. Finally, this query works.
Child.includes(:children_users).where(state: 'active', owner_id: self.id, "children_users.user_id" => other_user.id).load

Redmine plugin to send email on certain status change

My scenario an issue change status in "closed" and redmine must send an email to an email address
My constraint:
issue assignee could not change
email must be configurable by user administration
only one email for issue
I'm currently using Redmine 2.4.3 final and because I'm not able to find a setting or existing plugin to get this done, I'm writting down a plugin, here my code:
require 'mailer'
module IssueAssignToPlugin
class Hooks < Redmine::Hook::ViewListener
def controller_issues_edit_before_save(context={})
configuration = Setting.plugin_helloworldredmineplugin
if !configuration.nil? && configuration['enabled'] && !configuration['user_id'].blank? && !configuration['status_id'].blank?
issue = context[:issue]
status = IssueStatus.find(configuration['status_id'])
user = User.find(configuration['user_id'])
if !user.nil? && !issue.watched_by?(user)
if issue.status == status
#issue.add_watcher(user)
#journal = issue.journals.last
#journal = Journal.new(:journalized => issue, :user => user, :created_on => Time.now)
#journal.details << JournalDetail.new(:property => 'relation', :prop_key => 'label_relates_to', :value => 2)
#Mailer.deliver_issue_edit(journal)
#mail(to: user.mail, cc: user.mail, bbc: user.mail)
#Mailer.deliver_mail(mail)
#
#Your code goes here!
#
end
end
end
return ''
end
alias_method :controller_issues_bulk_edit_before_save, :controller_issues_edit_before_save
alias_method :controller_issues_new_before_save, :controller_issues_edit_before_save
end
end
As you can see I've tried many ways, but without luck.
Could someone please help me? My problem is "just" send an Email having only user.mail and using Redmine "settings"

Save each email before sending rails 4

I want to keep track of all triggered emails by the application into a db table, so that i can have a log which emails are sent and to whom.
Kindly suggest me the best possible solution.
I have solved this using the following way:
created a class in lib directory
class MyProjectMailLogger
def self.delivering_email(message)
#to = message.to.to_s
#subject = message.subject.to_s
#message = message.body.to_s
EmailQueue.create!(:receipient_email => #to, :subject => #subject, :message => #message, :email_status_id => 3)
end
end
In config/initalizers/setup_mail.rb
ActionMailer::Base.register_interceptor(MyProjectMailLogger)
You might need to add the following line in the application.rb file as its not include files from lib directory:
config.autoload_paths += %W(#{config.root}/lib)
Yay!! and i logged my emails.
I am doing some research on this and it seems like https://github.com/ankane/ahoy_email is a nice gem to accomplish this. It uses an interceptor internally like the accepted answer. It also integrates with a free event tracking library that has a number of different backends. Might be something to consider if you're starting something like this today.