Search Results

Search found 4088 results on 164 pages for 'params keyword'.

Page 52/164 | < Previous Page | 48 49 50 51 52 53 54 55 56 57 58 59  | Next Page >

  • Rails select box in form decides on create action in controller?

    - by dannymcc
    Hi Everyone? I am trying to add a select box to the base of my create form that decides if an action runs from the controller...if that makes any sense? Basically the application creates a project in FreeagentCentral whenever a new project is made: def create @company = Company.find(params[:kase][:company_id]) @kase = @company.kases.create!(params[:kase]) respond_to do |format| params[:send_to_freeagent] ? @kase.create_freeagent_project(current_user) #flash[:notice] = 'Case was successfully created.' flash[:notice] = fading_flash_message("Case was successfully created.", 5) format.html { redirect_to(@kase) } format.xml { render :xml => @kase, :status => :created, :location => @kase } end end and within my form I have: <%= check_box_tag :send_to_freeagent, 1 % Create project in Freeagent? What I would like to happen, is if the select box is checked the project is sent to Freeagent. If not, the case just gets created locally as normal but without the Freeagent data being sent. If I use the above code, I get an exception caught error: SyntaxError in KasesController#new controllers/kases_controller.rb:114: syntax error, unexpected '\n' Any idea what I am doing wrong, also is it possible to make the check boxes checked as default? Thanks, Danny

    Read the article

  • How do you search a document for a string in c++?

    - by Jeff
    Here's my code so far: #include<iostream> #include<string> #include<fstream> using namespace std; int main() { int count = 0; string fileName; string keyWord; string word; cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ; getline(cin, fileName); cout << endl; cout << "Please input the word you'd like to search for: " << endl; cin >> keyWord; cout << endl; ifstream infile(fileName.c_str()); while(infile.is_open()) { getline(cin,word); if(word == keyWord) { cout << word << endl; count++; } if(infile.eof()) { infile.close(); } } cout << count; } I'm not sure how to go to the next word, currently this infinite loops...any recommendation? Also...how do I tell it to print out the line that that word was on? Thanks in advance!

    Read the article

  • Nullable<T> as a parameter

    - by ferch
    I alredy have this: public static object GetDBValue(object ObjectEvaluated) { if (ObjectEvaluated == null) return DBNull.Value; else return ObjectEvaluated; } used like: List<SqlParameter> Params = new List<SqlParameter>(); Params.Add(new SqlParameter("@EntityType", GetDBValue(EntityType))); Now i wanted to keep the same interface but extend that to use it with nullable public static object GetDBValue(int? ObjectEvaluated) { if (ObjectEvaluated.HasValue) return ObjectEvaluated.Value; else return DBNull.Value; } public static object GetDBValue(DateTime? ObjectEvaluated) {...} but i want only 1 function GetDBValue for nullables. How do I do that and keep the call as is is? Is that possible at all? I can make it work like: public static object GetDBValue<T>(Nullable<T> ObjectEvaluated) where T : struct { if (ObjectEvaluated.HasValue) return ObjectEvaluated.Value; else return DBNull.Value; } But the call changes to: Params.Add(new SqlParameter("@EntityID ", GetDBValue<int>(EntityID)));

    Read the article

  • Adding Categories to my Articles in my Rails app (Small Help)

    - by user214038
    I'm currently building a semi-small ruby app for a project. The problem I'm currently facing is the following: I want to be Able to fit the Article into the Categories. I've already accomplish this by having two models. An article model with a foreign key of category_id and my Category model with the name of the category. With a has_one and belogs_to relationship. (We're assuming you can only fit an article into one category). Here's the piece of code. This is the new method, where i create a new article and load up all the categories. def new @article = Article.new @categories = Category.find(:all) end The problem comes when i try to get the category from a combo box in order to insert it along with the article. This is the combo box code : f.select(:category_id,@categories) And this is the create method: def create @category = Category.find(params[:id]) @article = @category.articles.new(params[:article]) if @article.save flash[:notice] = "Article Submitted Sucessfully" redirect_to user_path else render :action = 'new' end end I believe that the problem i have is in this line when i try to load up the selected category "@category = Category.find(params[:id])" because whenever i hardcode the this line into @category = Category.find(1) It Works perfectly

    Read the article

  • Rails ActionCaching with Memcached fragment hit but action gets called anyway

    - by baldtrol
    Hi stackoverflow. I'm running into something strange. I'm using memcached with a caches_action setup. I'm doing this in 4 different controllers. In two of them, it works flawlessly (so far), though admittedly those two controllers are less complicated than the two in which it doesn't seem to work. I'm doing something like this: caches_action :index, :expires_in => 6.hours, :cache_path => Proc.new {|controller| controller.send(:generate_cache_path) }, :layout => false, :if => Proc.new { |c| c.request.format.js? } The intention behind the above is to cache some results that are dependent on the params. my :generate_cache_path method just takes into account some params and session vars and creates a unique key for memcached. I can see in memcached -vv that this is working. What's weird is that I get my request from the rails app for a given key, and I see memcached (with -vv) get the request and send back the response. But then my action runs anyway, and a new value is then set for the same key, even when all the same params are given. I can watch it happen. In the controllers where everything is working, the request is made for the fragment, it gets it, and the action in the controller is halted, and the fragment is passed back. These lines come from the exact same request: Cached fragment hit: views/items/?page=1&rp=10&srtn=created_at&srto=DESC.js And then: Cached fragment miss: views/items/?page=1&rp=10&srtn=created_at&srto=DESC.js I don't know what to make of it, or if I'm doing something stupid. Any help or ideas where I could start looking for trouble would be greatly appreciated.

    Read the article

  • Sending mail through PHP

    - by Angeline Aarthi
    I'm trying to sends mails in PHP. The code I used for sending a mail in CakePHP is given below. I get the message 'Simple Email Sent' in my web page but the mail is not delivered to my inbox. Am I missing something? The values in the to, subject and link fields are set with the values entered in the user interface. $this->set('to',$this->params['form']['to']); $this->set('subject',$this->params['form']['subject']); $this->set('link',$this->params['form']['link']); $this->Email->to = to; $this->Email->subject = subject; $this->Email->from = '[email protected]'; $this->Email->delivery= 'mail'; $this->Email->sendAs='text'; $this->Email->template = 'simple_message'; //$this->Email->send(link); if ( $this->Email->send(link) ) { $this->Session->setFlash('Simple email sent'); } else { $this->Session->setFlash('Simple email not sent'); }

    Read the article

  • ViewGroup{TextView,...}.getMeasuredHeight gives wrong value is smaller than real height.

    - by Dewr
    ViewGroup(the ViewGroup is containing TextViews having long text except line-feed-character).getMeasuredHeight returns wrong value... that is smaller than real height. how to get rid of this problem? here is the java code: ;public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; int count = listAdapter.getCount(); for (int i = 0; i < count; i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(View.MeasureSpec.AT_MOST, View.MeasureSpec.UNSPECIFIED); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } ; and here is the list_item_comments.xml:; {RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" } {RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="8dip" android:layout_marginRight="8dip" } {TextView android:id="@+id/list_item_comments_nick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" style="@style/WhiteText" /} {TextView android:id="@+id/list_item_comments_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:textSize="16sp" style="@style/WhiteText" /} {TextView android:id="@+id/list_item_comments_content" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/list_item_comments_nick" android:autoLink="all" android:textSize="24sp" style="@style/WhiteText" /} {/RelativeLayout} {/RelativeLayout} ;

    Read the article

  • Filtering Questions (posts) by tag_name in TagController#index passing /tags?tag_name=something

    - by bgadoci
    I am trying to get my TagsController#index action to display only the Questions that contain certain tags when passing the search parameter tag_name. I am not getting an error just can't get the filter to work correctly such that upon receiving the /tags?tag_name=something url, only those questions are displayed . Here is the setup: class Tag < ActiveRecord::Base belongs_to :question def self.search(str) return [] if str.blank? cond_text = str.split.map{|w| "tag_name LIKE ? "}.join(" OR ") cond_values = str.split.map{|w| "%#{w}%"} all(:order => "created_at DESC", :conditions => (str ? [cond_text, *cond_values] : [])) end end and class Question < ActiveRecord::Base has_many :tags, :dependent => :destroy end tag link that would send the URL to the TagsController looks like this: <%= link_to(tag_name, tags_path(:tag_name => tag_name)) %> and outputs: /tags?tag_name=something In my /views/tags/index.html.erb view I am calling the questions by rendering a partial /views/questions/_question.html.erb. <%= render :partial => @questions %> When I send the URL with the search parameter nothing happens. Here is my TagsController#index action: def index @tags = Tag.search(params[:search]).paginate :page => params[:page], :per_page => 5 @tagsearch = Tag.search(params[:search]) @tag_counts = Tag.count(:group => :tag_name, :order => 'count_all DESC', :limit => 100) @questions = Question.all( :order => 'created_at DESC', :limit => 50) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @tags } end end How can I properly filter questions displayed in the /views/tags/index.html.erb file for the parameter tag.tag_name?

    Read the article

  • Facebook android app keeps crashing even though there are no errors in my code. Why?

    - by user1554479
    If you import the facebook SDK library, the code works (ignore the deprecated methods for now lol) and there are no errors or warnings. However, when I run my facebook app on my Android 2.2 or 4.2 emulator, the app crashes either upon opening or after the log on screen. Why? Is it because I'm not implementing Async Task? If so, how does that work? Here's my code: package com.sara.facebookappl; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.StrictMode; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.facebook.android.DialogError; import com.facebook.android.Facebook; import com.facebook.android.Facebook.DialogListener; import com.facebook.android.FacebookError; import com.facebook.android.Util; public class MainActivity extends Activity implements OnClickListener, DialogListener { Facebook fb; ImageView button; SharedPreferences sp; TextView welcome; Button post; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); post=(Button)findViewById(R.id.button1); String APP_ID = getString(R.string.APP_ID); fb= new Facebook(APP_ID); sp =getPreferences(MODE_PRIVATE); String access_token=sp.getString("access_token", null); long expires=sp.getLong("access_expires", 0); if (access_token !=null) { fb.setAccessToken(access_token); } if(expires !=0) { fb.setAccessExpires(expires); } button=(ImageView)findViewById(R.id.login); button.setOnClickListener((OnClickListener) this); updateButtonImage(); } @SuppressWarnings("deprecation") private void updateButtonImage() { // TODO Auto-generated method stub post.setVisibility(Button.VISIBLE); button.setImageResource(R.drawable.com_facebook_loginbutton_blue); //logout button if (fb.isSessionValid()) { button.setImageResource(R.drawable.com_facebook_loginbutton_blue); // ^logout button JSONObject obj=null; URL img_url =null; try { String jsonUser= fb.request("me"); obj = Util.parseJson(jsonUser); String id=obj.optString("id"); String name = obj.optString("name"); welcome.setText("Welcome, " + name); }catch(FacebookError e) { e.printStackTrace(); }catch (JSONException e) { e.printStackTrace(); }catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } }else { post.setVisibility(Button.VISIBLE); button.setImageResource(R.drawable.com_facebook_loginbutton_blue); } } @SuppressWarnings("deprecation") public void buttonClicks(View v) { switch (v.getId()) { case R.id.button1: //post Bundle params= new Bundle(); params.putString("name", "User X"); params.putString("caption", "Rating"); params.putString("description", "User X Rated"); params.putString("link", "http://..."); fb.dialog(MainActivity.this, "feed", params, new Facebook.DialogListener() { @Override public void onFacebookError(FacebookError e) { // TODO Auto-generated method stub } @Override public void onError(DialogError e) { // TODO Auto-generated method stub } @Override public void onComplete(Bundle values) { // TODO Auto-generated method stub } @Override public void onCancel() { // TODO Auto-generated method stub } }); break; } } @SuppressWarnings("deprecation") public void onClick(View v) { if(fb.isSessionValid()) { try { fb.logout(getApplicationContext()); updateButtonImage(); //button will close our our session }catch(MalformedURLException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } }else{ //login into facebook fb.authorize(MainActivity.this, new String[] {"email"}, new Facebook.DialogListener() { @Override public void onFacebookError(FacebookError e) { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_SHORT).show(); } @Override public void onError(DialogError e) { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show(); } @Override public void onComplete(Bundle values) { // TODO Auto-generated method stub Editor editor=sp.edit(); editor.putString("access_token", fb.getAccessToken()); editor.putLong("access_expires", fb.getAccessExpires()); editor.commit(); updateButtonImage(); } @Override public void onCancel() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show(); } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @SuppressWarnings("deprecation") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); fb.authorizeCallback(requestCode, resultCode, data); } @Override public void onComplete(Bundle values) { // TODO Auto-generated method stub } @Override public void onFacebookError(FacebookError e) { // TODO Auto-generated method stub } @Override public void onError(DialogError e) { // TODO Auto-generated method stub } @Override public void onCancel() { // TODO Auto-generated method stub } } LogCat Errors: 12-16 04:56:59.070: E/AndroidRuntime(822): FATAL EXCEPTION: main 12-16 04:56:59.070: E/AndroidRuntime(822): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sara.facebookappl/com.sara.facebookappl.MainActivity}: android.os.NetworkOnMainThreadException 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.access$600(ActivityThread.java:141) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.os.Handler.dispatchMessage(Handler.java:99) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.os.Looper.loop(Looper.java:137) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.main(ActivityThread.java:5039) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.lang.reflect.Method.invokeNative(Native Method) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.lang.reflect.Method.invoke(Method.java:511) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 12-16 04:56:59.070: E/AndroidRuntime(822): at dalvik.system.NativeStart.main(Native Method) 12-16 04:56:59.070: E/AndroidRuntime(822): Caused by: android.os.NetworkOnMainThreadException 12-16 04:56:59.070: E/AndroidRuntime(822): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 12-16 04:56:59.070: E/AndroidRuntime(822): at java.net.InetAddress.getAllByName(InetAddress.java:214) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnection.(HttpConnection.java:70) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnection.(HttpConnection.java:50) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177) 12-16 04:56:59.070: E/AndroidRuntime(822): at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.facebook.android.Util.openUrl(Util.java:219) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.facebook.android.Facebook.requestImpl(Facebook.java:806) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.facebook.android.Facebook.request(Facebook.java:732) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.sara.facebookappl.MainActivity.updateButtonImage(MainActivity.java:83) 12-16 04:56:59.070: E/AndroidRuntime(822): at com.sara.facebookappl.MainActivity.onCreate(MainActivity.java:63) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.Activity.performCreate(Activity.java:5104) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 12-16 04:56:59.070: E/AndroidRuntime(822): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 12-16 04:56:59.070: E/AndroidRuntime(822): ... 11 more 12-16 04:56:59.090: D/dalvikvm(822): GC_CONCURRENT freed 150K, 9% free 2723K/2988K, paused 7ms+58ms, total 239ms

    Read the article

  • Ruby on Rails: How to create associated models on the fly ?

    - by Misha Moroshko
    I have the following models: class Product < ActiveRecord::Base belongs_to :brand belongs_to :model accepts_nested_attributes_for :brand, :model ... end class Brand < ActiveRecord::Base has_many :products has_many :models ... end class Model < ActiveRecord::Base has_many :products belongs_to :brand accepts_nested_attributes_for :brand ... end I have a problem to create a new product. Here is the relevant code in the controller: class ProductsController < ApplicationController ... def create @product = Product.new(params[:product]) if @product.save ... # Here is the error end ... end When user adds a new brand and a new model, params[:product] contains the following: "brand_attributes"=>{"name"=>"my_new_brand"} "model_attributes"=>{"model_no"=>"my_new_model"} and I got the following error: Mysql2::Error: Column 'brand_id' cannot be null: INSERT INTO `models` ... because model has a foreign key brand_id which is not set. I can't set it because the brand (like the model) is created on the fly when the product is created. I don't want to create the brand before the product, because then I the product has errors, I will need to delete the created brand. Then I tried to change params[:product] like this: "brand_attributes"=>{"name"=>"my_new_brand", "model_attributes"=>{"model_no"=>"my_new_model"}} but I end up with this: unknown attribute: model_attributes What would be the proper way to handle this ?

    Read the article

  • Problem validating an XSD file: The content type of a derived type and that of its base must both be mixed or both be element-only

    - by Paulo Tavares
    Hi, I have following XML schema: <?xml version="1.0" encoding="UTF-8"?> <schema xmlns:netconf="urn:ietf:params:xml:ns:netconf:base:1.0" targetNamespace="urn:ietf:params:xml:ns:netconf:base:1.0" ... <complexType name="dataInlineType"> <xs:complexContent> <xs:extension base="xs:anyType"/> </xs:complexContent> </complexType> <complexType name="get-config_output_type__" > <complexContent> <extension base="netconf:dataInlineType"> <sequence> <element name="data"> <complexType> <sequence> <element name="__.get-config.output.data.A__" minOccurs="0" maxOccurs="unbounded" /> </sequence> </complexType> </element> <element name="__.get-config.A__" minOccurs="0" maxOccurs="unbounded"/> </sequence> </extension> </complexContent> And I getting the folling error: cos-ct-extends.1.4.3.2.2.1.a: The content type of a derived type and that of its base must both be mixed or both be element-only. Type 'get-config_output_type__' is element only, but its base type is not. If I put both elements mixed="true" I get another error: cos-nonambig: WC[##any] and "urn:ietf:params:xml:ns:netconf:base:1.0":data (or elements from their substitution group) violate "Unique Particle Attribution". During validation against this schema, ambiguity would be created for those two particles. I using the Eclipse to validate my schema, so what can I do?

    Read the article

  • Rails: Added new Action in Controller, but there is no path?

    - by Newbie
    Hello! I try to do following: A user is on his profile page. Now he edits his profile. He klicks on update and the data is saved. Now I want to redirect the user to another kind of profile-edit-page. I did the following in my users_controller.rb: def update @user = User.find(params[:id]) respond_to do |format| if @user.update_attributes(params[:user]) flash[:notice] = 'User was successfully updated.' if(@user.team_id != nil) format.html { redirect_to(@user) } else format.html { redirect_to choose_team_path } end format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity } end end end def choose_team @user = User.find(params[:id]) end I created a view: /users/choose_team.html.erb Now I get the following error: undefined local variable or method `choose_team_path' for #<UsersController:0x1f56650> So I added choose_team to my routes.rb: map.choose_team 'choose-team', :controller => 'users', :action => 'choose_team' Now, after submitting my first edit form, it redirects me to http://localhost:3000/choose-team and I get following error: Couldn't find User without an ID What I want: If a user has no team_id, he should be redirected to my choose_team.html.erb for choosing a team, else he should be redirected to his profile/show. How to do this?

    Read the article

  • Black Magic in Grails Data Binding!?

    - by Tiago Alves
    As described in http://n4.nabble.com/Grails-Data-Binding-for-One-To-Many-Relationships-with-REST-tp1754571p1754571.html i'm trying to automatically bind my REST data. I understand now that for one-to-many associations the map that is required for the data binding must have a list of ids of the many side such as: [propName: propValue, manyAssoc: [1, 2]] However, I'm getting this exception Executing action [save] of controller [com.example.DomainName] caused exception: org.springframework.orm.hibernate3.HibernateSystemException: IllegalArgumentException occurred calling getter of com.example.DomainName.id; nested exception is org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.example.DomainName.id However, even weirder is the update action that is generated for the controller. There we have the databinding like this: domainObjectInstance.properties = params['domainObject'] But, and this is the really weird thing, params['domainObject'] is null! It is null because all the domainObject fields are passed directly in the params map itself. If I change the above line to domainObjectInstance.properties = null the domainObject is still updated! Why is this happening and more important, how can I bind my incoming XML automatically if it comes in this format (the problem is the one-to-many associations): <product> <name>Table</name> <brand id="1" /> <categories> <category id="1" /> <category id="2" /> </categories> </product>

    Read the article

  • Trouble accessing data in relationships in Ember

    - by user3618430
    I'm having trouble saving data in this model relationship. My models are as follows: App.Flow = DS.Model.extend({ title: DS.attr('string'), content: DS.attr('string'), isCustom: DS.attr('boolean'), params: DS.hasMany('parameter', {async: true}) }); App.Parameter = DS.Model.extend({ flow: DS.belongsTo('flow'), param: DS.attr('string'), param_tooltip: DS.attr('string'), param_value: DS.attr('string') }); As you can see, I want Flows to have multiple Parameters. I have a rudimentary setup using Flow and Parameter fixtures, which behave as expected in the templates. However, when I try to create new ones in the controller, I have trouble setting the flow and parameter values correctly. var p = this.store.createRecord('parameter', { param: "foo", param_tooltip: "world", param_value: "hello" }); var f = this.store.createRecord('flow', { title: 'job', content: title, isCustom: true, params: [p] // doesn't seem to work }); f.set('params', [p]); // doesn't seem to work p.set('flow', f); // also doesn't seem to work // Save the new model p.save(); f.save(); I've tried a lot of solutions after staring at this and StackOverflow for a while (not just the ones listed). I'm not really sure what to try next. One thing that I noticed in the Ember inspector was that the ids of these created elements were not integers (they were something like the string 'fixture_0'), but I'm not really sure why that would be, whether its related, or how to fix it. Thanks!

    Read the article

  • How do I avoid a race condition in my Rails app?

    - by Cathal
    Hi, I have a really simple Rails application that allows users to register their attendance on a set of courses. The ActiveRecord models are as follows: class Course < ActiveRecord::Base has_many :scheduled_runs ... end class ScheduledRun < ActiveRecord::Base belongs_to :course has_many :attendances has_many :attendees, :through => :attendances ... end class Attendance < ActiveRecord::Base belongs_to :user belongs_to :scheduled_run, :counter_cache => true ... end class User < ActiveRecord::Base has_many :attendances has_many :registered_courses, :through => :attendances, :source => :scheduled_run end A ScheduledRun instance has a finite number of places available, and once the limit is reached, no more attendances can be accepted. def full? attendances_count == capacity end attendances_count is a counter cache column holding the number of attendance associations created for a particular ScheduledRun record. My problem is that I don't fully know the correct way to ensure that a race condition doesn't occur when 1 or more people attempt to register for the last available place on a course at the same time. My Attendance controller looks like this: class AttendancesController < ApplicationController before_filter :load_scheduled_run before_filter :load_user, :only => :create def new @user = User.new end def create unless @user.valid? render :action => 'new' end @attendance = @user.attendances.build(:scheduled_run_id => params[:scheduled_run_id]) if @attendance.save flash[:notice] = "Successfully created attendance." redirect_to root_url else render :action => 'new' end end protected def load_scheduled_run @run = ScheduledRun.find(params[:scheduled_run_id]) end def load_user @user = User.create_new_or_load_existing(params[:user]) end end As you can see, it doesn't take into account where the ScheduledRun instance has already reached capacity. Any help on this would be greatly appreciated.

    Read the article

  • My IF statement is changing variables in PHP

    - by user1902509
    I am fairly new to the whole programming thing, so forgive me if this is a stupid question. It seems odd that I haven't run into it before. I am trying to make an order form for a cake. You fill out the form, submit it, and it will then display the order in a new window, where you then hit "submit," and upload it to the Database. I have a series of If Statements to check for errors in the form before submitting it. Here is a simplified version of the code. Writing means any writing you want on the cake, Name is your name, and cake is what type of cake you want (the default is "None"). try { $name = trim($params->name); $cake = trim($params->cake); $writing = trim($params->writing); if (strlen($name) < 3){ throw new Exception("Please enter Your name."); } if ($cake = "None") { throw new Exception("Please select a Cake" } if ($cake = "Caramel Apple Pie" or $cake = "Pumpkin Pie" or $cake = "Eggnog Pie" and strlen($writing) > 1) { throw new Exception("We are sorry, but you can't write on any of our specialty pies."); } } catch(Exception $x) { $error = $x->getmessage(); } So what is happening is that when I go and hit submit the first time, the correct cake type comes up, but when you submit it the second time, the error comes up saying that I have "None" selected. All the other values are there and remain the same. I think the problem is that the first "IF" statement (Where it says "If($cake = "None")) is automatically changing $cake to "None" because I have tried commenting just that statement out, and it will then change the cake to be "Caramel Apple Pie," which is in the top of the next IF statement. Anyone know why it is doing this? And how to fix it?

    Read the article

  • Change URL Submitted to Depending on Form Selection

    - by Chris
    I have a form which I need to submit to one of three different URLs depending on a selection made in the form. I suspect the easiest solution is to use jQuery to insert the appropriate path before the rest of the form parameters as the selection is made, but not sure on what the code would be. Any pointers greratly appreciated! <form id="myForm" action='/booking/default-path' accept-charset='utf-8' method='get'> <select name="paramA" id="paramA"> <option id="optionA" value="A" selected="selected">Option A</option> <option id="optionB" value="B">Option B</option> </select> <select name="currency" id="currency"> <option id="GBP" value="GBP" selected="selected">British Pounds</option> <option id="EUR" value="EUR">Euros</option> <option id="USD" value="USD">US Dollars</option> </select> <input type="submit" value="submit" id="submit" name="submit" /> </form> Where the three different URLs would be: ../booking/default-path-gbp?...[params here]... ../booking/default-path-eur?...[params here]... ../booking/default-path-usd?...[params here]... I know it would be a lot easier to incorporate the parameter in the usual way and just use one submission URL root, but unfortunately I'm submitting to an eComms system out of my control and am stuck with having to find a solution to this. Should be easy I think, but not sure where to start, jQuery used elsewhere, so would prefer to use this framework in any solutions.

    Read the article

  • Asynchronous javascript issue

    - by amit
    I am trying to create a function which takes values from various html elements of the page to create a string and pass on to a variable. now this works great for all browsers except IE 8 and 9. IE tends to skip the part of fetching the values and goes straight to the variable and finds nothing.. is there a way to sync it all so that it works in IE? function seturl() { var qstring = returnQString(); $('span.keyword').text($.trim($('#hdnKeyWord').attr('value'))); $('input.search_box').attr('value', $.trim($('#hdnKeyWord').attr('value'))); $('#hdnSearchKeyword').attr('value', $.trim($('#hdnKeyWord').attr('value'))); $(".search_box").val($.trim($("#hdn_span_hdnKeyWord").text())); $(".header_inner input[type='text']").focus(); $(".search_term input[type='text']").focus(); $('#locationurl').attr('value', qstring); } function returnQString(){ var qstring = $.trim($('#locationurl').attr('init')); //initial value of the url qstring += "?type=" + $('#hdnSTSearch').attr('value'); // type of handler hit qstring += "&keyword=" + encodeURIComponent($('#hdnKeyWord').attr('value')); // keyword addition qstring += "&pagestart=" + $('#current_page').attr('value'); // pagestart(current page) addition qstring += "&pagesize=" + $('#show_per_page').attr('value'); // per page size addition qstring += "&facets=" // facetsearch $.each(selectedFilter.items, function (index, value) { qstring += value.filter + ","; }); qstring += "&selectedSection=" + selectedSection // Section Select return qstring; }

    Read the article

  • Pass arguments to a parameter class object

    - by David R
    This is undoubtedly a simple question. I used to do this before, but it's been around 10 years since I worked in C++ so I can't remember properly and I can't get a simple constructor call working. The idea is that instead of parsing the args in main, main would create an object specifically designed to parse the arguments and return them as required. So: Parameters params = new Parameters(argc, argv) then I can call things like params.getfile() Only problem is I'm getting a complier error in Visual Studio 2008 and I'm sure this is simple, but I think my mind is just too rusty. What I've got so far is really basic: In the main: #include "stdafx.h" #include "Parameters.h" int _tmain(int argc, _TCHAR* argv[]) { Parameters params = new Parameters(argc, argv); return 0; } Then in the Parameters header: #pragma once class Parameters { public: Parameters(int, _TCHAR*[]); ~Parameters(void); }; Finally in the Parameters class: include "Stdafx.h" #include "Parameters.h" Parameters::Parameters(int argc, _TCHAR* argv[]) { } Parameters::~Parameters(void) { } I would appreciate if anyone could see where my ageing mind has missed the really obvious. Thanks in advance.

    Read the article

  • Problems with Getting Remote Contents using Google App Engine

    - by dade
    Here is the client side code. It is running insdide a Google Gadgets var params = {}; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON; var url = "http://invplatformtest.appspot.com/getrecent/"; gadgets.io.makeRequest(url, response, params); The response function is: function response(obj) { var r = obj.data; alert(r['name']); } while on the server end, the python code sending the JSON is: class GetRecent(webapp.RequestHandler): def get(self): self.response.out.write({'name':'geocities'}) #i know this is where the problem is so how do i encode json in GAE? which is just supposed to send back a Json encoded string but when i run this, the javascript throws the following error: r is null alert(r['name']); If i were recieving just TEXT contents and my server send TEXT everything works fine. I only get this problem when am trying to send JSON. Where exactly is the problem? Am i encoding the JSON the wrong way on AppEngine? I tried using the JSON library but it looks as if this is not supported. Where is the problem exactly? :(

    Read the article

  • JQuery to PHP function and back Ajaxed

    - by Xaris
    Hi all, i have a set of php function that i want to call on different events mostly onclick with jquery async (ajax). The first function is called on load $(document).ready(function() { $("#div2").hide('slow'); $("#div1").empty().html('<img src="ajax-loader.gif" />'); $.ajax( { type: "POST", url: "WebFunctions.php", data: {'func':'1'}, success: function(html) { $("#div1").show('slow').html(html) } }); The Data: {'func':'1'} -- is a switch statement on the php side switch($_POST['func']) { case '1': getParents(); break; case '2': getChilds(params); break; case '3': getChildObjects(params); break; default: } "This functions are calls to a soap server" <-- irrelevant. So when that function finishes i get an array which contains IDs and Names. I echo the names but i want the ID for reference so when i click on the echoed name i can call an other php function with parameter the ID of the name... How do i get rid of the switch statement?? How do i call properly php functions and pass params to it??? How can i save this IDs so when i click on an item with that id an other php function is called?? Plz feel free to ask any question, any answer is welcome :)

    Read the article

  • Need some advice on MVC separation..

    - by Zenph
    I should note I am using Zend Framework. Although this shouldn't affect the concrete answer, it does mean there are several places I can implement my following method (action helper, controller etc). The issue is I have buildOptions() and parseOptions() method which takes $_GET/$_POST variables based on a 'tag' and builds rules which are then used in a select query. An example would be ?modelSort=id&modelOrder=asc The 'model' in the above obviously relates to the particular model, and it used as a 'tag' so that I can for example also have model2Sort and model2Order so there is no conflict between parameters. However, the trouble I am having now is where should these methods go? They are generally dealing with request params. I have been reading a lot about fat model, thin controller. Should this be in an abstract model. My thinking was that if it were, I would do something like: (note, I know I wouldn't call directly like this. Method would be used by child classes) $abstractModel-buildOptions($params); Where 'params' could be anything, like the request parameters $_GET or $_POST: $abstractModel-buildOptions($_GET); Now from what I can see the model is not inherintly dealing with request variables but rather parameters passed to the method. Advice? Where does this method belong? Model, Controller? Specifically on Zend, should it be an action helper, plugin, within an abstract model? Appreciate any advice.

    Read the article

  • Why null reference exception in SetMolePublicInstance?

    - by OldGrantonian
    I get a "null reference" exception in the following line: MoleRuntime.SetMolePublicInstance(stub, receiverType, objReceiver, name, null); The program builds and compiles correctly. There are no complaints about any of the parameters to the method. Here's the specification of SetMolePublicInstance, from the object browser: SetMolePublicInstance(System.Delegate _stub, System.Type receiverType, object _receiver, string name, params System.Type[] parameterTypes) Here are the parameter values for "Locals": + stub {Method = {System.String <StaticMethodUnitTestWithDeq>b__0()}} System.Func<string> + receiverType {Name = "OrigValue" FullName = "OrigValueP.OrigValue"} System.Type {System.RuntimeType} objReceiver {OrigValueP.OrigValue} object {OrigValueP.OrigValue} name "TestString" string parameterTypes null object[] I know that TestString() takes no parameters and returns string, so as a starter to try to get things working, I specified "null" for the final parameter to SetMolePublicInstance. As already mentioned, this compiles OK. Here's the stack trace: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.ExtendedReflection.Collections.Indexable.ConvertAllToArray[TInput,TOutput](TInput[] array, Converter`2 converter) at Microsoft.Moles.Framework.Moles.MoleRuntime.SetMole(Delegate _stub, Type receiverType, Object _receiver, String name, MoleBindingFlags flags, Type[] parameterTypes) at Microsoft.Moles.Framework.Moles.MoleRuntime.SetMolePublicInstance(Delegate _stub, Type receiverType, Object _receiver, String name, Type[] parameterTypes) at DeqP.Deq.Replace[T](Func`1 stub, Type receiverType, Object objReceiver, String name) in C:\0VisProjects\DecP_04\DecP\DeqC.cs:line 38 at DeqPTest.DecCTest.StaticMethodUnitTestWithDeq() in C:\0VisProjects\DecP_04\DecPTest\DeqCTest.cs:line 28 at Starter.Start.Main(String[] args) in C:\0VisProjects\DecP_04\Starter\Starter.cs:line 14 Press any key to continue . . . To avoid the null parameter, I changed the final "null" to "parameterTypes" as in the following line: MoleRuntime.SetMolePublicInstance(stub, receiverType, objReceiver, name, parameterTypes); I then tried each of the following (before the line): int[] parameterTypes = null; // if this is null, I don't think the type will matter int[] parameterTypes = new int[0]; object[] parameterTypes = new object[0]; // this would allow for various parameter types All three attempts produce a red squiggly line under the entire line for SetMolePublicInstance Mouseover showed the following message: The best overloaded method match for 'Microsoft.Moles.Framework.Moles.MoleRuntime.SetMolePublicInstance(System.Delegate, System.Type, object, string, params System.Type[])' has some invalid arguments. I'm assuming that the first four arguments are OK, and that the problem is with the params array.

    Read the article

  • PUT-ing a form to update a row, but I can't find the id. Where is it?

    - by montooner
    How should I be passing in the ID? Error: Couldn't find Product without an ID Form: <% form_for :product, @product, :url => { :action => :update } do |f| %> <%= f.error_messages %> <p> <%= f.label :names %><br /> <%= f.text_field :names %> </p> <p> <%= f.submit 'Update' %> </p> <% end %> Controller (for /products/edit/1 view): def edit @product = Product.find(params[:id]) end Controller (to change the db): def update @product = Product.find(params[:id]) respond_to do |format| if @product.update_attributes(params[:product]) format.html { redirect_to(@product, :notice => 'Product was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @product.errors, :status => :unprocessable_entity } end end end

    Read the article

  • Need help with simple NHibernate mapping...

    - by mplarsen
    Need help with a simple NHibernate relationship... Tables/Classes Request ------- RequestId Title … Keywords ------- RequestID (key) Keyword (key) Request mapping file <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="CR.Model" assembly="CR"> <class name="CR.Model.Request, CR table="[dbo].[Request]" lazy="true"> <id name="Id" column="[RequestID]"> <generator class="native" /> </id> <property name="RequestorID" column="[RequestorID]" /> <property name="RequestorOther" column="[RequestorOther]" /> … Keyword?? </class> </hibernate-mapping> How do I simply map multiple keywords to a request? I don't need another mapping file for the keyword class, do I? It's be great if I could not only get the associated keywords, but add them too...

    Read the article

< Previous Page | 48 49 50 51 52 53 54 55 56 57 58 59  | Next Page >