Search Results

Search found 1033 results on 42 pages for 'destroy'.

Page 11/42 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Authlogic Current User Question - hiding admin links...

    - by bgadoci
    I think I am missing something while using the Authlogic gem w/ Rails. To set the stage I have multiple users and each user can create posts and comments. Upon the display of a post or comment I would like to give the user who created them the option to edit or destroy. I am successfully using the following code to hide and show elements based on if a user is logged in or not but can't seem to find out how to only show these links to the actual user who created them...not any user that is logged in. <% if current_user %> <%= link_to 'Edit', edit_question_path(question) %> | <%= link_to 'Destroy', question, :confirm => 'Are you sure?', :method => :delete %> <% else %> <p>nothing to see here</p> <% end %> Here is the def of current_user located in the application controller in case I need to change something here. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time protect_from_forgery # See ActionController::RequestForgeryProtection for details# helper_method :current_user private def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.record end end

    Read the article

  • SQL Server 2008 alternative for SQL-DMO

    - by alexdelpiero
    Hi! I previously was using SQL-DMO to automatically generate scripts from the database. Now I upgraded to SQL Server 2008 and I don’t want to use this feature anymore since Microsoft will be dropping this feature off. Is there any other alternative I can use to connect to a server and generate scripts automatically from a database? Any answer is welcome. Thanks in advance. This is the procedure i was previously using: CREATE PROC GenerateSP ( @server varchar(30) = null, @uname varchar(30) = null, @pwd varchar(30) = null, @dbname varchar(30) = null, @filename varchar(200) = 'c:\script.sql' ) AS DECLARE @object int DECLARE @hr int DECLARE @return varchar(200) DECLARE @exec_str varchar(2000) DECLARE @spname sysname SET NOCOUNT ON -- Sets the server to the local server IF @server is NULL SELECT @server = @@servername -- Sets the database to the current database IF @dbname is NULL SELECT @dbname = db_name() -- Sets the username to the current user name IF @uname is NULL SELECT @uname = SYSTEM_USER -- Create an object that points to the SQL Server EXEC @hr = sp_OACreate 'SQLDMO.SQLServer', @object OUT IF @hr <> 0 BEGIN PRINT 'error create SQLOLE.SQLServer' RETURN END -- Connect to the SQL Server IF @pwd is NULL BEGIN EXEC @hr = sp_OAMethod @object, 'Connect', NULL, @server, @uname IF @hr <> 0 BEGIN PRINT 'error Connect' RETURN END END ELSE BEGIN EXEC @hr = sp_OAMethod @object, 'Connect', NULL, @server, @uname, @pwd IF @hr <> 0 BEGIN PRINT 'error Connect' RETURN END END --Verify the connection EXEC @hr = sp_OAMethod @object, 'VerifyConnection', @return OUT IF @hr <> 0 BEGIN PRINT 'error VerifyConnection' RETURN END SET @exec_str = 'DECLARE script_cursor CURSOR FOR SELECT name FROM ' + @dbname + '..sysobjects WHERE type = ''P'' ORDER BY Name' EXEC (@exec_str) OPEN script_cursor FETCH NEXT FROM script_cursor INTO @spname WHILE (@@fetch_status <> -1) BEGIN SET @exec_str = 'Databases("'+ @dbname +'").StoredProcedures("'+RTRIM(UPPER(@spname))+'").Script(74077,"'+ @filename +'")' EXEC @hr = sp_OAMethod @object, @exec_str, @return OUT IF @hr <> 0 BEGIN PRINT 'error Script' RETURN END FETCH NEXT FROM script_cursor INTO @spname END CLOSE script_cursor DEALLOCATE script_cursor -- Destroy the object EXEC @hr = sp_OADestroy @object IF @hr <> 0 BEGIN PRINT 'error destroy object' RETURN END GO

    Read the article

  • Jquery Cluetip - clean up between ajax loaded content

    - by ted776
    Hi, I'm using the jquery cluetip plugin and trying to figure out how to remove any open cluetip dialogs once i load new content via ajax. I am either stuck with the dialog boxes still showing on top of new content, or the ways i've tried to fix this actually remove all future cluetip dialogs from showing at all. Here's my code, thanks for any help. On dom ready i instantiate cluetip as below. //activate cluetip $('a.jTip').cluetip({ attribute: 'href', cluetipClass: 'jtip', arrows: true, activation: 'click', ajaxCache: false, dropShadow: true, sticky: true, mouseOutClose: false, closePosition: 'title' }); When i'm loading new content, I have the following code. The problem i have is that $('.cluetip-jtip').empty() prevents dialog boxes from opening on any of the new content loaded in, while the destroy function doesn't remove any open dialog boxes, but just destroys the current object. $('.next a').live("click", function(){ var toLoad = $(this).attr('href'); var $data = $('#main_body #content'); $.validationEngine.closePrompt('body'); //close any validation messages $data.fadeOut('fast', function(){ $data.load(toLoad, function(){ $data.animate({ opacity: 'show' }, 'fast'); //reinitialise datepicker and toolip $(".date").date_input(); //JT_init(); $('.hidden').hide(); //scroll to top of form $("html,body").animate({ "scrollTop": $('#content').offset().top + "px" }); //remove existing instance //$('a.jTip').cluetip('destroy'); //remove any opened popups $('.cluetip-jtip').empty(); //reinitialise cluetip $('a.jTip').cluetip({ attribute: 'href', cluetipClass: 'jtip', arrows: true, activation: 'click', ajaxCache: false, dropShadow: true, sticky: true, mouseOutClose: false, closePosition: 'title' }); }); }); return false; });

    Read the article

  • Ruby-on-rails: routing problem: controller action looks for show when it should look for finalize

    - by cbrulak
    background: trying to use the twitter gem for ruby-on-rails. in routes: map.resources :twitter_sessions map.finalize_twitter_sessions 'twitter_sessions/finalize', :controller => 'twitter_sessions', :action => 'finalize' (twitter_sessions is the controller for the twitter sessions in my app). The view has one file new.html.erb and is very simple: <% form_tag(twitter_sessions_path) do |f| %> <p><%= submit_tag "twitter!" %></p> <% end %> and the twitter_sessions_controller.rb: def new end def create oauth.set_callback_url(finalize_twitter_sessions_url) session['rtoken'] = oauth.request_token.token session['rsecret'] = oauth.request_token.secret redirect_to oauth.request_token.authorize_url end def destroy reset_session redirect_to new_session_path end def finalize oauth.authorize_from_request(session['rtoken'], session['rsecret'], params[:oauth_verifier]) profile = Twitter::Base.new(oauth).verify_credentials session['rtoken'] = session['rsecret'] = nil session[:atoken] = oauth.access_token.token session[:asecret] = oauth.access_token.secret sign_in(profile) redirect_back_or root_path end However, after I click the "twitter" button, I get this error: 401 Unauthorized .../gems/oauth-0.3.6/lib/oauth/consumer.rb:200:in `token_request' .../gems/oauth-0.3.6/lib/oauth/consumer.rb:128:in `get_request_token' .../gems/twitter-0.9.2/lib/twitter/oauth.rb:32:in `request_token' .../gems/twitter-0.9.2/lib/twitter/oauth.rb:25:in `set_callback_url' app/controllers/twitter_sessions_controller.rb:7:in `create' If I go to the finalize url, http://localhost:3000/twitter_sessions/finalize, directly, I get this error: Unknown action No action responded to show. Actions: create, destroy, finalize, isLoggedInToBeta, login_required, and new Any ideas? Thanks

    Read the article

  • How to make a thread that runs at x:00 x:15 x:30 and x:45 do something different at 2:00.

    - by rmarimon
    I have a timer thread that needs to run at a particular moments of the day to do an incremental replication with a database. Right now it runs at the hour, 15 minutes past the hour, 30 minutes past the hour and 45 minutes past the hour. This is the code I have which is working ok: public class TimerRunner implements Runnable { private static final Semaphore lock = new Semaphore(1); private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); public static void initialize() { long delay = getDelay(); executor.schedule(new TimerRunner(), delay, TimeUnit.SECONDS); } public static void destroy() { executor.shutdownNow(); } private static long getDelay() { Calendar now = Calendar.getInstance(); long p = 15 * 60; // run at 00, 15, 30 and 45 minutes past the hour long second = now.get(Calendar.MINUTE) * 60 + now.get(Calendar.SECOND); return p - (second % p); } public static void replicate() { if (lock.tryAcquire()) { try { Thread t = new Thread(new Runnable() { public void run() { try { // here is where the magic happens } finally { lock.release(); } } }); t.start(); } catch (Exception e) { lock.release(); } } else { throw new IllegalStateException("already running a replicator"); } } public void run() { try { TimerRunner.replicate(); } finally { long delay = getDelay(); executor.schedule(new TimerRunner(), delay, TimeUnit.SECONDS); } } } This process is started by calling TimerRunner.initialize() when a server starts and calling TimerRunner.destroy(). I have created a full replication process (as opposed to incremental) that I would like to run at a certain moment of the day, say 2:00am. How would change the above code to do this? I think that it should be very simple something like if it is now around 2:00am and it's been a long time since I did the full replication then do it now, but I can't get the if right. Beware that sometimes the replicate process takes way longer to complete. Sometimes beyond the 15 minutes, posing a problem in running at around 2:00am.

    Read the article

  • boost::shared_ptr in Objective-C++

    - by John Smith
    This is a better understanding of a question I had earlier. I have the following Objective-C++ object @interface OCPP { MyCppobj * cppobj; } @end @implementation OCPP -(OCPP *) init { cppobj = new MyCppobj; } @end Then I create a completely differently obj which needs to use cppobj in a boost::shared_ptr (I have no choice in this matter, it's part of a huge library which I cannot change) @interface NOBJ -(void) use_cppobj_as_shared_ptr { //get an OCPP obj called occ from somewhere.. //troubling line here } @end I have tried the following and that failed: I tried synthesising cppobj. Then I created a shared_ptr in "troubling line" in the following way: MyCppobj * cpp = [occ cppobj]; bsp = boost::shared_ptr<MyCppobj>(cpp); It works fine first time around. Then I destroy the NOBJ and recreate it. When I for cppobj it's gone. Presumably shared_ptr decided it's no longer needed and did away with it. So I need help. How can I keep cppobj alive? Is there a way to destroy bsp (or it's reference to cppobj) without destroying cppobj?

    Read the article

  • Devise routes to only use custom sign in page

    - by eblume
    I am trying to learn Devise and seem to have hit a problem that is nearly the same as many, many questions here on SO but just slightly different enough that I am not getting much traction following those questions' threads. I have a very simple application. Users can sign in and sign out (and also the devise 'forgot password' stuff is enabled - I am not concerned about it at this time) and that is it. They can't register, they can't edit their profile other than to change their password, they can't do anything except sign in and sign out. (Account creation will, for now, be handled manually at the command line.) I would vastly prefer that the only page that users can log in from was "/" (root_path). I already have it working where you can log in from "/", and that is great. The problem I am having is that if you type in your user/password combination incorrectly from the root_path login page, it automatically sends you to the Devise sign-in page to continue trying to sign in. How can I make Devise redirect to root_path on sign-in failure? Here are my routes - they are probably not optimal or correctly configured and I would appreciate pointers on fixing them: root to: "core_pages#splash" devise_for :users, skip: [:sessions] as :user do # get 'signin' => 'devise/sessions#new', as: :new_user_session post 'signin' => 'devise/sessions#create', as: :user_session delete 'signout' => 'devise/sessions#destroy', as: :destroy_user_session, via: Devise.mappings[:user].sign_out_via end match '/home' => 'core_pages#home' Note the commented-out 'get signin' line. The system works without this line but, surprisingly (to me), "GET /signin" results in a HTTP 400 (OK) response and renders the Devise login template. I would prefer it return some sort of 'invalid request' or just silently redirect the user to root_path. Running rake routes on these routes gives: root / core_pages#splash user_password POST /users/password(.:format) devise/passwords#create new_user_password GET /users/password/new(.:format) devise/passwords#new edit_user_password GET /users/password/edit(.:format) devise/passwords#edit PUT /users/password(.:format) devise/passwords#update user_session POST /signin(.:format) devise/sessions#create destroy_user_session DELETE /signout(.:format) devise/sessions#destroy home /home(.:format) core_pages#home Thanks!

    Read the article

  • Database nesting layout confusion

    - by arzon
    I'm no expert in databases and a beginner in Rails, so here goes something which kinda confuses me... Assuming I have three classes as a sample (note that no effort has been made to address any possible Rails reserved words issue in the sample). class File < ActiveRecord::Base has_many :records, :dependent => :destroy accepts_nested_attributes_for :records, :allow_destroy => true end class Record < ActiveRecord::Base belongs_to :file has_many :users, :dependent => :destroy accepts_nested_attributes_for :users, :allow_destroy => true end class User < ActiveRecord::Base belongs_to :record end Upon entering records, the database contents will appear as such. My issue is that if there are a lot of Files for the same Record, there will be duplicate record names. This will also be true if there will be multiple Records for the same user in the the Users table. I was wondering if there is a better way than this so as to have one or more files point to a single Record entry and one or more Records will point to a single User. BTW, the File names are unique. Files table: id name 1 name1 2 name2 3 name3 4 name4 Records table: id file_id record_name record_type 1 1 ForDaisy1 ... 2 2 ForDonald1 ... 3 3 ForDonald2 ... 4 4 ForDaisy1 ... Users table: id record_id username 1 1 Daisy 2 2 Donald 3 3 Donald 4 4 Daisy Is there any way to optimize the database to prevent duplication of entries, or this should really the correct and proper behavior. I spread out the database into different tables to be able to easily add new columns in the future.

    Read the article

  • Creating has_many :through records 2x times

    - by antiarchitect
    I have models class Question < ActiveRecord::Base WEIGHTS = %w(medium hard easy) belongs_to :test has_many :answers, :dependent => :destroy has_many :testing_questions end class Testing < ActiveRecord::Base belongs_to :student, :foreign_key => 'user_id' belongs_to :subtest has_many :testing_questions, :dependent => :destroy has_many :questions, :through => :testing_questions end So when I try to bind questions to testing on it's creation: >> questions = Question.all ... >> questions.count => 3 >> testing = Testing.create(:user_id => 3, :subtest_id => 1, :questions => questions) Testing Columns (0.9ms) SHOW FIELDS FROM `testings` SQL (0.1ms) BEGIN SQL (0.1ms) COMMIT SQL (0.1ms) BEGIN Testing Create (0.3ms) INSERT INTO `testings` (`created_at`, `updated_at`, `user_id`, `subtest_id`) VALUES('2010-05-18 00:53:05', '2010-05-18 00:53:05', 3, 1) TestingQuestion Columns (0.9ms) SHOW FIELDS FROM `testing_questions` TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(1, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31) TestingQuestion Create (0.4ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(2, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31) TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(3, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31) TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(1, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31) TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(2, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31) TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(3, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31) SQL (90.2ms) COMMIT => #<Testing id: 31, subtest_id: 1, user_id: 3, created_at: "2010-05-18 00:53:05", updated_at: "2010-05-18 00:53:05"> There is 6 SQL queries and 6 records in testing_questions are created. Why?

    Read the article

  • Crash generated during destruction of hash_map

    - by Alien01
    I am using hash_map in application as typedef hash_map<DWORD,CComPtr<IInterfaceXX>> MapDword2Interface; In main application I am using static instance of this map static MapDword2Interface m_mapDword2Interface; I have got one crash dump from one of the client machines which point to the crash in clearing this map I opened that crash dump and here is assembly during debugging > call std::list<std::pair<unsigned long const ,ATL::CComPtr<IInterfaceXX> >,std::allocator<std::pair<unsigned long const ,ATL::CComPtr<IInterfaceXX> > > >::clear > mov eax,dword ptr [CMainApp::m_mapDword2Interface+8 (49XXXXX)] Here is code where crash dump is pointing. Below code is from stl:list file void clear() { // erase all #if _HAS_ITERATOR_DEBUGGING this->_Orphan_ptr(*this, 0); #endif /* _HAS_ITERATOR_DEBUGGING */ _Nodeptr _Pnext; _Nodeptr _Pnode = _Nextnode(_Myhead); _Nextnode(_Myhead) = _Myhead; _Prevnode(_Myhead) = _Myhead; _Mysize = 0; for (; _Pnode != _Myhead; _Pnode = _Pnext) { // delete an element _Pnext = _Nextnode(_Pnode); this->_Alnod.destroy(_Pnode); this->_Alnod.deallocate(_Pnode, 1); } } Crash is pointing to the this->_Alnod.destroy(_Pnode); statement in above code. I am not able to guess it, what could be reason. Any ideas??? How can I make sure, even is there is something wrong with the map , it should not crash?

    Read the article

  • Why the composite component fails to parent controls?

    - by lyborko
    Hi, I created my own Component : TPage , which Contains Subcomponent TPaper (TPanel). The problem is, that when I put controls such as TMemo or TButton on the TPaper (which fills up nearly whole area), the controls do not load at all. see example below TPaper = class(TPanel) protected constructor Create(AOwner: TComponent);override; destructor Destroy;override; public procedure Paint; override; end; TPage = class(TCustomControl) private FPaper:TPaper; protected procedure CreateParams(var Params:TCreateParams); override; public constructor Create(AOwner: TComponent);override; destructor Destroy;override; published property Paper: TPaper read FPaper write FPaper; end; constructor TPage.Create(AOwner: TComponent); begin inherited Create(AOwner); PaperOrientation:=poPortrait; PaperSize:=psA4; PaperBrush:=TBrush.Create; PaperBrush.Color:=clWhite; PDFDocument:=Nil; FPaper:=TPaper.Create(Self); FPaper.Parent:=Self; FPaper.SetSubComponent(True); end; ... Memo1 is parented in TPaper (TPanel) at design-time, but after pressing "Run" it does not exist. procedure TForm1.btn1Click(Sender: TObject); begin if not Assigned(Memo1) then ShowMessage('I do not exist'); //Memo1 is nil end; Have you any idea what's wrong? Thanks a lot P.S Delphi 7 When I put TMemo inside TPaper and save the unit (Unit1), after inspection of associated dfm file, there is no trace of TMemo component. (Thats why it can not load to app.)

    Read the article

  • Rails: Getting rid of "X is invalid" validation errors

    - by DJTripleThreat
    I have a sign-up form that has nested associations/attributes whatever you want to call them. My Hierarchy is this: class User < ActiveRecord::Base acts_as_authentic belongs_to :user_role, :polymorphic => true end class Customer < ActiveRecord::Base has_one :user, :as => :user_role, :dependent => :destroy accepts_nested_attributes_for :user, :allow_destroy => true validates_associated :user end class Employee < ActiveRecord::Base has_one :user, :as => :user_role, :dependent => :destroy accepts_nested_attributes_for :user, :allow_destroy => true validates_associated :user end I have some validation stuff in these classes as well. My problem is that if I try to create and Customer (or Employee etc) with a blank form I get all of the validation errors I should get plus some Generic ones like "User is invalid" and "Customer is invalid" If I iterate through the errors I get something like: user.login can't be blank User is invalid customer.whatever is blah blah blah...etc customer.some_other_error etc etc Since there is at least one invalid field in the nested User model, an extra "X is invalid" message is added to the list of errors. This gets confusing to my client and so I'm wondering if there is a quick way to do this instead of having to filer through the errors myself.

    Read the article

  • How to change a Linux user password from python

    - by Vaulor
    I'm having problems with changing a Linux user's password from python. I've tried so many things, but I couldn't manage to solve the issue, here is the sample of things I've already tried: sudo_password is the password for sudo, sudo_command is the command I want the system to run, user is get from a List and is the user who I want to change the password for, and newpass is the pass I want to assign to 'user' user = list.get(ANCHOR) sudo_command = 'passwd' f = open("passwordusu.tmp", "w") f.write("%s\n%s" % (newpass, newpass)) f.close() A=os.system('echo -e %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user)) print A windowpass.destroy() 'A' is the return value for the execution of os.system, in this case 256. I tried also A=os.system('echo %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user)) but it returns the same error code. I tried several other ways with 'passwd' command, but whithout succes. With 'chpasswd' command I 've tried this: user = list.get(ANCHOR) sudo_command = 'chpasswd' f = open("passwordusu.tmp", "w") f.write("%s:%s" % (user, newpass)) f.close() A=os.system('echo %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user)) print A windowpass.destroy() also with: A=os.system('echo %s|sudo -S %s:%s|%s' % (sudo_password, user, newpass, sudo_command)) @;which returns 32512 A=os.system("echo %s | sudo -S %s < \"%s\"" % (sudo_password, sudo_command, "passwordusu.tmp")) @;which returns 256 I tried 'mkpasswd' and 'usermod' too like this: user = list.get(ANCHOR) sudo_command = 'mkpasswd -m sha-512' os.system("echo %s | sudo -S %s %s > passwd.tmp" % (sudo_password,sudo_command, newpass)) sudo_command="usermod -p" f = open('passwd.tmp', 'r') for line in f.readlines(): newpassencryp=line f.close() A=os.system("echo %s | sudo -S %s %s %s" % (sudo_password, sudo_command, newpassencryp, user)) @;which returns 32512 but, if you go to https://www.mkpasswd.net , hash the 'newpass' and substitute for 'newpassencryp', it returns 0 which theoretically means it has gone right, but so far it doesn't changes the password. I've searched on internet and stackoverflow for this issue or similar and tried what solutions exposed, but again,without success. I would really apreciate any help, and of course, if you need more info i'll be glad to supply it! Thanks in advance.

    Read the article

  • duplicate rows in join table with has_many => through and accepts_nested_attributes_for

    - by shalako
    An event has many artists, and an artist has many events. The join of an artist and an event is called a performance. I want to add artists to an event. This works except that I'm getting duplicate entries into my join table when creating a new event. This causes problems elsewhere. event.rb has_many :performances, :dependent => :destroy has_many :artists, :through => :performances accepts_nested_attributes_for :artists, :reject_if => proc {|a| a['name'].blank?} accepts_nested_attributes_for :performances, :reject_if => proc { |a| a['artist_id'].blank? }, :allow_destroy => true artist.rb has_many :performances, :dependent => :destroy has_many :artists, :through => :performances performance.rb belongs_to :artist belongs_to :event events_controller.rb def new @event = Event.new @event.artists.build respond_to do |format| format.html # new.html.erb format.xml { render :xml => @event } end end def create @event = Event.new(params[:event]) respond_to do |format| if @event.save flash[:notice] = 'Event was successfully created.' format.html { redirect_to(admin_events_url) } format.xml { render :xml => @event, :status => :created, :location => @event } else format.html { render :action => "new" } format.xml { render :xml => @event.errors, :status => :unprocessable_entity } end end end output Performance Create (0.2ms) INSERT INTO `performances` (`event_id`, `artist_id`) VALUES(7, 19) Performance Create (0.1ms) INSERT INTO `performances` (`event_id`, `artist_id`) VALUES(7, 19)

    Read the article

  • Passing params in rails... Breakthrough in understanding params, aka, the "aha" moment

    - by Brian McDonough
    I have a simple has_many belongs_to relationship and I want to include the parent object for the view of the belongs_to model and I have had some success, but I want it to work better. class Submission < ActiveRecord::Base belongs_to :user belongs_to :contest end class Contest < ActiveRecord::Base belongs_to :user has_many :submissions, :dependent => :destroy end In the case that works, I pass contest_id to submissions by placing it in the url: <%= link_to 'Submit Contest Entry', new_submission_path(:contest_id => @contest.id), :class => 'btn btn-primary btn-large mleft10' %> So that, combined with a hidden_field: <%= f.hidden_field :contest_id %> And a find_contest method in the controller (called with a before_filter): def find_contest #the next line is giving the error (line 76) @contest = Contest.find(params[:submission][:contest_id]) end Makes it work for submissions/new, but how do I add a find to the controller that just works across more than that one page, like if I want to access in show and index. Right now, I get an error: Started GET "/submissions?contest_id=5" for 127.0.0.1 at 2012-12-01 16:01:45 -0800 Processing by SubmissionsController#index as HTML Parameters: {"contest_id"=>"5"} User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY users.created_at DESC LIMIT 1 Completed 500 Internal Server Error in 37ms NoMethodError (undefined method `[]' for nil:NilClass): app/controllers/submissions_controller.rb:76:in `find_contest' [edited] Adding show action for submissions: before_filter :find_contest, :except => [:index, :show, :edit, :update, :destroy] def find_contest @contest = Contest.find(params[:submission][:contest_id]) end def show contest_id = @submission.contest_id @submission = @commentable = Submission.find(params[:id]) @comments = @commentable.comments.order(:created_at).reverse respond_to do |format| format.html # show.html.erb format.json { render :json => @submission } end end

    Read the article

  • Rails: Getting rid of generic "X is invalid" validation errors

    - by DJTripleThreat
    I have a sign-up form that has nested associations/attributes whatever you want to call them. My Hierarchy is this: class User < ActiveRecord::Base acts_as_authentic belongs_to :user_role, :polymorphic => true end class Customer < ActiveRecord::Base has_one :user, :as => :user_role, :dependent => :destroy accepts_nested_attributes_for :user, :allow_destroy => true validates_associated :user end class Employee < ActiveRecord::Base has_one :user, :as => :user_role, :dependent => :destroy accepts_nested_attributes_for :user, :allow_destroy => true validates_associated :user end I have some validation stuff in these classes as well. My problem is that if I try to create and Customer (or Employee etc) with a blank form I get all of the validation errors I should get plus some Generic ones like "User is invalid" and "Customer is invalid" If I iterate through the errors I get something like: user.login can't be blank User is invalid customer.whatever is blah blah blah...etc customer.some_other_error etc etc Since there is at least one invalid field in the nested User model, an extra "X is invalid" message is added to the list of errors. This gets confusing to my client and so I'm wondering if there is a quick way to do this instead of having to filer through the errors myself.

    Read the article

  • Rails 3 : Can't get form_for to work as a 'delete' following the RESTful achitecture => always giving a ROUTING ERROR

    - by Alex
    I have a very simple render that goes as follow: <%= form_for(:relationships, :url => relationships_path, :html => {:method => 'delete'}) do |f| %> <div><%= f.hidden_field :user_id_to_unfollow, :value => @user.id %></div> <div class="actions"><%= f.submit "Unfollow" %></div> <% end %> When I submit this form it will always give me a Routing Error No route matches "/relationships" on my page. In my relationships controller, I have created all the propers methods: def create ... end def destroy ... end def update ... end def show ... end And in my routes config I have made sure to allow all routes for the relationships controller resources :relationships But I can't seem to get into the destroy method of the controller :( However if I remove the :html => {:method => 'delete'} method parameter in the form_for then I get to the create method of the controller no pb. I don't get it.... Alex

    Read the article

  • CanCan polymorphic resource access problem

    - by Call 'naive' True
    Hi everybody, i don't quite understand how to restrict access to links in this particular case with CanCan. I always get "Edit" link displayed. So i believe the problem is in my incorrect definition of cancan methods(load_ and authorize_). I have CommentsController like that: class CommentsController < ApplicationController before_filter :authenticate_user! load_resource :instance_name => :commentable authorize_resource :article def index @commentable = find_commentable #loading our generic object end ...... private def find_commentable params.each { |name, value| if name =~ /(.+)_id$/ return $1.classify.constantize.includes(:comments => :karma).find(value) end } end end and i have in comments/index.html.erb following code that render file from other controller: <%= render :file => "#{get_commentable_partial_name(@commentable)}/show.html.erb", :collection => @commentable %> you can think about "#{get_commentable_partial_name(@commentable)}" like just "articles" in this case. Content of "articles/show.html.erb": <% if can? :update, @commentable %> <%= link_to 'Edit', edit_article_path(@commentable) %> | <% end %> my ability.rb: class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user if user.role? :admin can :manage, :all elsif user.role? :author can :read, [Article, Comment, Profile] can :update, Article, :user_id => user.id end end end relations with models is: class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true, :dependent => :destroy ... end class Article < ActiveRecord::Base has_many :comments, :as => :commentable, :dependent => :destroy ... end i have tried debug this issue like that user = User.first article = Article.first ability = Ability.new(user) ability.can?(:update, article) and i always get "= true" in ability check Note: user.role == author and article.user_id != user.id if you need more information please write thank's for your time && sorry for my english

    Read the article

  • Why rails app is redirecting unexpectedly instead of matching the route?

    - by ruevaughn
    I asked this question earlier and thought it was fixed, but it's not. Previous question here My problem is I am trying to set my routes so that when I type in localhost:3000/sites/admin It should redirect to localhost:3000/en/sites/admin here is my routes.rb file scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do get "log_out" => "sessions#destroy", as: "log_out" get "log_in" => "sessions#new", as: "log_in" resources :sites, except: [:new, :edit, :index, :show, :update, :destroy, :create] do collection do get :home get :about_us get :faq get :discounts get :services get :contact_us get :admin get :posts end end resources :users resources :abouts resources :sessions resources :coupons resources :monthly_posts resources :reviews resources :categories do collection { post :sort } resources :children, :controller => :categories, :only => [:index, :new, :create, :new_subcategory] end resources :products do member do put :move_up put :move_down end end resources :faqs do collection { post :sort } end root :to => 'sites#home' match "/savesort" => 'sites#savesort' end match '', to: redirect("/#{I18n.default_locale}") match '*path', to: redirect("/#{I18n.default_locale}/%{path}") But as of right now, it redirects to /en/en/en/en/en/en/en/en/en/en/sites/admin (adds en until browser complains). Any thoughts why it keeps adding /en?

    Read the article

  • How to split up levels? (cocos2d,box2d,iphone) to save CPU and memory?

    - by cocos2dbeginner
    Hi, so I'm going to create large levels. But there's a problem: There's much unseen space (it's a jump'n run like mario bros.) and this will use memory + cpu. so how could I split up my levels? I'm using Box2D+ cocos2d for iphone. Any ideas? Mayby just set the visible property to NO? But it would be still in the memory :(. But what with the box2d bodies? Destroy and recreate them would be to heavy for the FPS, because I have physics built in which should not be recreated. Should I make fix points where i want to split the level up, than if the player is 200 px away it should preload it. and if the player is 200 px away from the last part of the level I unload it. But there would be the problem with the physics, because on the start of the level it has a unique movement and later if i destroy and recreate it it would do the same. but i don't want that. other ideas?

    Read the article

  • Paperclip: Stay put on edit

    - by EricR
    When a user edits something in my application, they're forced to re-upload their image via paperclip even if they aren't changing it. Failing to do so will cause an error, since I validate_presence_of :image. This is quite annoying. How can I make it so Paperclip won't update its attributes if a user simply doesn't supply a new image on an edit? The photo controller is fresh out of Rails' scaffold generator. The rest of the source code is provided below. models/accommodation.rb class Accommodation < ActiveRecord::Base attr_accessible :photo validates_presence_of :photo has_one :photo has_many :notifications belongs_to :user accepts_nested_attributes_for :photo, :allow_destroy => true end controllers/accommodation_controller.rb class AccommodationsController < ApplicationController def index @accommodations = Accommodation.all end def show @accommodation = Accommodation.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:error] = "Accommodation not found." redirect_to :home end def new @accommodation = current_user.accommodations.build @accommodation.build_photo end def create @accommodation = current_user.accommodations.build(params[:accommodation]) if @accommodation.save flash[:notice] = "Successfully created your accommodation." redirect_to @accommodation else @accommodation.build_photo render :new end end def edit @accommodation = Accommodation.find(params[:id]) @accommodation.build_photo rescue ActiveRecord::RecordNotFound flash[:error] = "Accommodation not found." redirect_to :home end def update @accommodation = Accommodation.find(params[:id]) if @accommodation.update_attributes(params[:accommodation]) flash[:notice] = "Successfully updated accommodation." redirect_to @accommodation else @accommodation.build_photo render :edit end end def destroy @accommodation = Accommodation.find(params[:id]) @accommodation.destroy flash[:notice] = "Successfully destroyed accommodation." redirect_to :inkeep end end models/photo.rb class Photo < ActiveRecord::Base attr_accessible :image, :primary belongs_to :accommodation has_attached_file :image, :styles => { :thumb=> "100x100#", :small => "150x150>" } end

    Read the article

  • How to access widgets created within functions in later function calls in Qt

    - by Inanepenguin
    So currently I have code, in C++, that creates a few QLabels, a QLineEdit, and a QCheckBox when a selection is made from a QComboBox. However, I would like to be able to access the widgets I have created in a later function to destroy them if a new selection is made from the combo box. I am able to access the objects created from using the Designer by doing ui-Object but i am not able to do that with objects created by using my own code. Can I do that some how, because I know how to work with that. In short, I would like to be able to dynamically create/destroy QWidgets based on selections made by the user. Is there a reference I should know of to do this, or any documentation? Or am I just completely going about this the wrong way? Here is the code I presently have for creating the objects: if (eventType == QString::fromStdString("Birthday")) { QLabel *label1 = new QLabel ("Celebrant: "); QLabel *label2 = new QLabel ("Surprise: "); QLineEdit *lineEdit = new QLineEdit; QCheckBox *box = new QCheckBox; ui->gridLayout->addWidget(label1,3,0,1,1, 0); ui->gridLayout->addWidget(label2,4,0,1,1,0); ui->gridLayout->addWidget(lineEdit,3,1,1,1,0); ui->gridLayout->addWidget(box,4,1,1,2,0); }

    Read the article

  • wxPython: MainLoop() seems to hang

    - by BandGap
    Hi all, my problem stems from the use of wxApp as far as I can tell. Inside a litte subroutine I call a wx.MessageDialog to ask for a yes or no. I retrieve the answer an process some stuff acordingly. My example code below actually works (though it might be ugly) except that the Dialog box stays open after hitting one of the buttons... import wx from os import path def HasFile(filename): if path.isfile(filename ): app = wx.App() dial = wx.MessageDialog(None, 'Die Datei "'+filename+'" wurde gefunden.\nSoll sie eingelesen werden?', 'Bitte antworten', wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION) result = dial.ShowModal() dial.EndModal(retCode=0) dial.Destroy() app.MainLoop() return result == wx.ID_YES else: return False So while the rest of the program does whatever is expected, the box just sits there. It also seems like my calls to matplotlib later on are producing errors (a Tkinter error to be precise), maybe because of the wx stuff? Edit: I tried to end the app with a call to app.Destroy(). This doesn't change the fact that the box is still there. When I issue a app.IsActive() afterwards the whole program exits (almost like a sys.exit())! How come? Edit 2: Adding a wxApp like this isn't a good idea since the other scripts get affected as well. Subsequent plotting commands don't get displayed and I don't know how to fix this. Thus I decided to remove the DialogBox alltogether.

    Read the article

  • Rails nested attributes with a join model, where one of the models being joined is a new record

    - by gzuki
    I'm trying to build a grid, in rails, for entering data. It has rows and columns, and rows and columns are joined by cells. In my view, I need for the grid to be able to handle having 'new' rows and columns on the edge, so that if you type in them and then submit, they are automatically generated, and their shared cells are connected to them correctly. I want to be able to do this without JS. Rails nested attributes fail to handle being mapped to both a new record and a new column, they can only do one or the other. The reason is that they are a nested specifically in one of the two models, and whichever one they aren't nested in will have no id (since it doesn't exist yet), and when pushed through accepts_nested_attributes_for on the top level Grid model, they will only be bound to the new object created for whatever they were nested in. How can I handle this? Do I have to override rails handling of nested attributes? My models look like this, btw: class Grid < ActiveRecord::Base has_many :rows has_many :columns has_many :cells, :through => :rows accepts_nested_attributes_for :rows, :allow_destroy => true, :reject_if => lambda {|a| a[:description].blank? } accepts_nested_attributes_for :columns, :allow_destroy => true, :reject_if => lambda {|a| a[:description].blank? } end class Column < ActiveRecord::Base belongs_to :grid has_many :cells, :dependent => :destroy has_many :rows, :through => :grid end class Row < ActiveRecord::Base belongs_to :grid has_many :cells, :dependent => :destroy has_many :columns, :through => :grid accepts_nested_attributes_for :cells end class Cell < ActiveRecord::Base belongs_to :row belongs_to :column has_one :grid, :through => :row end

    Read the article

  • How do i close a socket after a timeout in node.js?

    - by rramsden
    I'm trying to close a socket after a connection times out after 1000ms. I am able to set a timeout that gets triggered after a 1000ms but I can't seem to destroy the socket... any ideas? var connection = http.createClient(80, 'localhost'); var request = connection.request('GET', '/somefile.xml', {'host':'localhost'}); var start = new Date().getTime(); request.socket.setTimeout(1000); request.socket.addListener("timeout", function() { request.socket.destroy(); sys.puts("socket timeout connection closed"); }); request.addListener("response", function(response) { var responseBody = []; response.setEncoding("utf8"); response.addListener("data", function(chunk) { sys.puts(chunk); responseBody.push(chunk); }); response.addListener("end", function() { }); }); request.end(); returns socket timeout connection closed node.js:29 if (!x) throw new Error(msg || "assertion error"); ^ Error: assertion error at node.js:29:17 at Timer.callback (net:152:20) at node.js:204:9

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >