Search Results

Search found 9437 results on 378 pages for 'rails newbie'.

Page 96/378 | < Previous Page | 92 93 94 95 96 97 98 99 100 101 102 103  | Next Page >

  • Rails with JQuery DIV manipulation

    - by MrThomas
    Say I have a loop of objects (style.cover.pic) in a DIV .style_image <% @styles.each do |style| % <div class="style_image"> <%=link_to (image_tag style.cover.pic.url(:small)), style %></div> With the use of JQuery On a click event I want to load (this.href) in to the div .style_image which was click not all of the .style_image DIV's. this is what I have done so fare: $(function() { $(".style_image a").live('click', function(event) { $(".style_image a").load(this.href + " #show_style"); $.get(this.href, null, null, "script"); return false; }); }); Can this be done? and yes how??? Regards Dan

    Read the article

  • Ruby on Rails form_remote_tag missing template

    - by Donald Hughes
    I'm using form_remote_tag(:url => {:controller => "home", :action => "search"}, :update => "mydiv"). When I click submit on the form "mydiv" is populated with the error "Template is missing. Missing template home/search.erb in view path app/views". I've tried multiple render options in def search, but they all result in the same error. It looks like the search method is trying to use it's default render even though I'm specifying what I want. I've tried: render 'index' render :text => 'Return this from my method!' Is my url incorrect? Is it not submitting back to my home controller's search method?

    Read the article

  • Rails AR validates_uniqueness_of against polymorphic relationship

    - by aaronrussell
    Is it posible to validate the uniqueness of a child model's attribute scoped against a polymorphic relationship? For example I have a model called field that belongs to fieldable: class Field < ActiveRecord::Base belongs_to :fieldable, :polymorphic => :true validates_uniqueness_of :name, :scope => :fieldable_id end I have several other models (Pages, Items) which have many Fields. So what I want is to validate the uniqueness of the field name against the parent model, but the problem is that occasionally a Page and an Item share the same ID number, causing the validations to fail when they shouldn't. Am I just doing this wrong or is there a better way to do this?

    Read the article

  • Rails can't render polymorphic associations to XML?

    - by ambertch
    When I render XML with an :include clause for a polymorphic association I have, it doesn't work. I end up with the XML returning the object pointers instead of the actual objects, like: <posts> #<Comment:0x102ed1540>#<Comment:0x102ecaa38>#<Comment:0x102ec7fe0>#<Comment:0x102ec3cd8> </posts> Yet as_json works! When I render JSON with :include clause, the associations are rendered correctly and I get something like: posts":[ {"type":"Comment","created_at":"2010-04-20T23:02:30-07:00","id":7,"content":"fourth comment"}, {"type":"Comment","created_at":"2010-04-20T23:02:26-07:00","id":6,"content":"third comment"}] My current workaround is using XML builder, but I'm not too comfortable with that in the long run. Does anyone happen to know about this issue? I'm kind of in a catch-22 because while XML doesn't render the associations, as_json doesn't render in a kosher json format (returns an array rather than a list of hashes as proper json should) and the deserializer I'm using on the client side would require modification to parse the json correctly.

    Read the article

  • Ignoring a model with all blank fields in Ruby on Rails

    - by aguynamedloren
    I am trying to create multiple items (each with a name value and a content value) in a single form. The code I have is functioning, but I cannot figure out how to ignore items that are blank. Here's the code: #item.rb class Item < ActiveRecord::Base attr_accessible :name, :content validates_presence_of :name, :content end #items_controller.rb class ItemsController < ApplicationController def new @items = Array.new(3){ Item.new } end def create @items = params[:items].values.collect{|item|Item.new(item)} if @items.each(&:save!) flash[:notice] = "Successfully created item." redirect_to root_url else render :action => 'new' end end #new.html.erb <% form_tag :action => 'create' do %> <%@items.each_with_index do |item, index| %> <% fields_for "items[#{index}]", item do |f| %> <p> Name: <%= f.text_field :name %> Content: <%= f.text_field :content %> </p> <% end %> <% end %> <%= submit_tag %> <% end %> This code works when all fields for all items are filled out in the form, but fails if any fields are left blank (due to validations). The goal is that 1 or 2 items could be saved, even if others are left blank. I'm sure there is a simple solution to this, but I've been tinkering for hours with no avail. Any help is appreciated!

    Read the article

  • Including inline javascript using content_for in rails

    - by TenJack
    I am using content_for and yeild to inject javascript files into the bottom of my layout but am wondering what the best practice is for including inline javascript. Specifically I'm wondering where the put the script type declaration: <% content_for :javascript do %> <script type="text/javascript"> ... </script> <% end %> or <% content_for :javascript do %> ... <% end %> <script type="text/javascript"> <%= yield :javascript %> </script> <% end %> I am using the first option now and wondering if it is bad to include multiple ... declarations within one view. Sometimes I have partials that lead to this.

    Read the article

  • rails routes for permalink with namespaced class

    - by David
    this one in my routes works perfectly: map.connect ':permalink', :controller = 'pages', :action = 'show' for this class: class PagesController < BackendController and on /xxx/pages it is shown like this: <%= link_to "#{item.link_name}", {:controller = :pages, :action = :show, :permalink = item.permalink} % which will generate a link like "how-to-create-permalinks". but i decided to move the PagesController into a subdirectory so the class is now written like so: class Backend::PagesController < BackendController But how does the route look like now? And how do i display it on the template so it links using the permalink? Thanks!

    Read the article

  • Rails 3.1. Cocoon link_to_add_association example needed

    - by BazZy
    pls show any example of using Cocoon's 'link_to_add_association' with html_options. https://github.com/nathanvda/cocoon Documentation says: html_options: extra html-options (see link_to) There are two extra options that allow to conrol the placement of the new link-data: data-association-insertion-node : the jquery selector of the node data-association-insertion-position : insert the new data before or after the given node. But i can not understand what to do, if i want insert partial just before my "add element" link. Not just after parent's div begin. This not gonna work: <%= link_to_add_association "add element", f, :production_years, :position = "after_all" %

    Read the article

  • memcached never expired in rails?

    - by pickerel
    It's very strange that the session will never expire if i use memcached store even i set config.action_controller.session :session_expires = 1.seconds.from_now And I use extended_fragment_cache to cache fragment, I meet the same problem <% Cache "my_page", {:expires = 1.minutes} do ... % never expired! Anyone know where's the problem?

    Read the article

  • Rails - 1 entry in model per field, per day

    - by Elliot
    Lets say I have a food model in the model, every day, people enter how many lbs of pizza/vegetables/fruit they eat. each food is its own column my issue is, I'd like it so they can only enter that in once (for that food type) every 24 hours (based on created_at). This possible?

    Read the article

  • DRYing Search Logic in Rails

    - by Kevin Sylvestre
    I am using search logic to filter results on company listing page. The user is able to specify any number of parameters using a variety of named URLs. For example: /location/mexico /sector/technology /sector/financial/location/argentina Results in the following respectively: params[:location] == 'mexico' params[:sector] == 'technology' params[:sector] == 'financial' and params[:location] == 'argentina' I am now trying to cleanup or 'DRY' my model code. Currently I have: def self.search(params) ... if params[:location] results = results.location_permalink_equals params[:location] if results results = Company.location_permalink_equals params[:location] unless results end if params[:sector] results = results.location_permalink_equals params[:sector] if results results = Company.location_permalink_equals params[:sector] unless results end ... end I don't like repeating the searchs. Any suggestions? Thanks.

    Read the article

  • Ruby on Rails field_for Form Helper Problems

    - by schone
    Hi all, I'm using the field_for form helper with a loop: <% f.fields_for :permissions do |permission_form| %> <tr> <td><%= permission_form.object.security_module.name %><%= permission_form.hidden_field(:security_module_id) %></td> <td><%= permission_form.object.security_module.description %></td> <tr> <% end %> The resulting output of the above code is this: <input id="role_permissions_attributes_0_id" name="role[permissions_attributes][0][id]" type="hidden" value="76" /> <tr> <td>Diary<input id="role_permissions_attributes_0_security_module_id" name="role[permissions_attributes][0][security_module_id]" type="hidden" value="13" /></td> <td>Access to the Diary Module</td> </tr> <!-- next input field then <tr> tag --> The problem with this markup is that the input tag falls outside of the tr tag which there for causes validation issues with XHTML. Does anyone know how I can have the input tag fall inside the tr tag therefore giving me valid XHTML 1.0 STRICT markup? Thanks

    Read the article

  • Rails ActiveRecord::MultiparameterAssignmentErrors

    - by Neil Middleton
    I have the following code in my model: attr_accessor :expiry_date validates_presence_of :expiry_date, :on => :create, :message => "can't be blank" and the following in my view: <%= date_select :account, :expiry_date, :discard_day => true, :start_year => Time.now.year, :end_year => Time.now.year + 15, :order => [:month, :year] %> However, when I submit my form I get: ActiveRecord::MultiparameterAssignmentErrors in SignupController#create /Users/x/.rvm/gems/ruby-1.8.6-p383/gems/activerecord-2.3.5/lib/active_record/base.rb:3073:in `execute_callstack_for_multiparameter_attributes' /Users/x/.rvm/gems/ruby-1.8.6-p383/gems/activerecord-2.3.5/lib/active_record/base.rb:3028:in `assign_multiparameter_attributes' /Users/x/.rvm/gems/ruby-1.8.6-p383/gems/activerecord-2.3.5/lib/active_record/base.rb:2750:in `attributes=' /Users/x/.rvm/gems/ruby-1.8.6-p383/gems/activerecord-2.3.5/lib/active_record/base.rb:2438:in `initialize' Any ideas as to what the problem might be? I've looked at #93277 with no joy, so am kinda stuck. Adding day to the select does NOT resolve the issue. Any ideas?

    Read the article

  • Rails: Helpers and Models - where to organize code

    - by Sam
    More and more I'm putting all of my code in models and helpers concerning MVC. However, sometimes I'm not sure where to organize code. Should it go into the model or should it go into a helper. What are the benefits of each. Is one faster or are they the same. I've heard something about all models getting cached so it seems then like that would be a better place to put most of my code. For example here is a scenario that works in a model or in helper: def status if self.purchased "Purcahsed" elsif self.confirmed "Confirmed" elsif self.reserved "Reserved" else "Pending" end end I don't need to save this status as in the database because there are boolean fields for purchased, and confirmed, and reserved. So why put this in a model or why put it into a helper? So I'm not sure of the best practice or benefits gained on putting code into a model or into helper if it can be in both.

    Read the article

  • Sorting/Paginating/Filtering Complex Multi-AR Object Tables in Rails

    - by Matt Rogish
    I have a complex table pulled from a multi-ActiveRecord object array. This listing is a combined display of all of a particular user's "favorite" items (songs, messages, blog postings, whatever). Each of these items is a full-fledged AR object. My goal is to present the user with a simplified search, sort, and pagination interface. The user need not know that the Song has a singer, and that the Message has an author -- to the end user both entries in the table will be displayed as "User". Thus, the search box will simply be a dropdown list asking them which to search on (User name, created at, etc.). Internally, I would need to convert that to the appropriate object search, combine the results, and display. I can, separately, do pagination (mislav will_paginate), sorting, and filtering, but together I'm having some problems combining them. For example, if I paginate the combined list of items, the pagination plugin handles it just fine. It is not efficient since the pagination is happening in the app vs. the DB, but let's assume the intended use-case would indicate the vast majority of the users will have less than 30 favorited items and all other behavior, server capabilities, etc. indicates this will not be a bottleneck. However, if I wish to sort the list I cannot sort it via the pagination plugin because it relies on the assumption that the result set is derived from a single SQL query, and also that the field name is consistent throughout. Thus, I must sort the merged array via ruby, e.g. @items.sort_by{ |i| i.whatever } But, since the items do not share common names, I must first interrogate the object and then call the correct sort by. For example, if the user wishes to sort by user name, if the sorted object is a message, I sort by author but if the object is a song, I sort by singer. This is all very gross and feels quite un-ruby-like. This same problem comes into play with the filter. If the user filters on the "parent item" (the message's thread, the song's album), I must translate that to the appropriate collection object method. Also gross. This is not the exact set-up but is close enough. Note that this is a legacy app so changing it is quite difficult, although not impossible. Also, yes there is some DRY that can be done, but don't focus on the style or elegance of the following code. Style/elegance of the SOLUTION is important, however! :D models: class User < ActiveRecord::Base ... has_and_belongs_to_many :favorite_messages, :class_name => "Message" has_and_belongs_to_many :favorite_songs, :class_name => "Song" has_many :authored_messages, :class_name => "Message" has_many :sung_songs, :class_name => "Song" end class Message < ActiveRecord::Base has_and_belongs_to_many :favorite_messages belongs_to :author, :class_name => "User" belongs_to :thread end class Song < ActiveRecord::Base has_and_belongs_to_many :favorite_songs belongs_to :singer, :class_name => "User" belongs_to :album end controller: def show u = User.find 123 @items = Array.new @items << u.favorite_messages @items << u.favorite_songs # etc. etc. @items.flatten! @items = @items.sort_by{ |i| i.created_at } @items = @items.paginate :page => params[:page], :per_page => 20 end def search # Assume user is searching for username like 'Bob' u = User.find 123 @items = Array.new @items << u.favorite_messages.find( :all, :conditions => "LOWER( author ) LIKE LOWER('%bob%')" ) @items << u.favorite_songs.find( :all, :conditions => "LOWER( singer ) LIKE ... " ) # etc. etc. @items.flatten! @items = @items.sort_by{ |i| determine appropriate sorting based on user selection } @items = @items.paginate :page => params[:page], :per_page => 20 end view: #index.html.erb ... <table> <tr> <th>Title (sort ASC/DESC links)</th> <th>Created By (sort ASC/DESC links))</th> <th>Collection Title (sort ASC/DESC links)</th> <th>Created At (sort ASC/DESC links)</th> </tr> <% @items.each |item| do %> <%= render { :partial => "message", :locals => item } if item.is_a? Message %> <%= render { :partial => "song", :locals => item } if item.is_a? Song %> <%end%> ... </table> #message.html.erb # shorthand, not real ruby print out message title, author name, thread title, message created at #song.html.erb # shorthand print out song title, singer name, album title, song created at

    Read the article

  • Rails, Deleting Children without Deleting Parent using :has_many

    - by Dex
    I have a model called MyContainer, which :has_many MyObjects. I want to delete all the MyObjects in the container without having to delete the MyContainer. My model does have :dependent = :destroy, however I don't want to have to delete and re-create the object because it is slower. Something like this does not work: @obj = MyContainer.find_by_id(10) @obj.my_objects.delete_all How can I accomplish this?

    Read the article

  • Custom Rails actions: I have issues every time

    - by normalocity
    Every time I go to add a custom action to a controller, I completely screw it up somehow. I'm trying to add a route "listings/buyer_listings", that will display all of my listings where someone is a buyer (rather than a seller). With the routes.rb file below, when I go to "listings/buyer_listings", I get routed instead to "users" WTF? In the past, I've had to define my routes using "map.", but this seems like a very verbose way to do something that should work with the :collection specification. You can see that I've done this with many routes as specified toward the end of the file, such as "edit_my_profile", etc. If I put the ":collection" part last my browser routes to the "show" action, which is not the correct action, and which also doesn't make sense to me why it would even do this. If I do "rake routes", my routes look correctly mapped. If I go into a Ruby console and have it recognize the url, it maps to the correct action, so what am I missing? ActionController::Routing::Routes.draw do |map| map.resources :locations map.resources :browse_boxes map.resources :tags map.resources :ratings map.resources :listings, :collection => { :buyer_listings => :get }, :has_many => :bids, :has_many => :comments map.resources :users map.resources :invite_requests map.resource :user_session map.resource :account, :controller => "users" map.root :controller => "listings", :action => "index" # optional, this just sets the root route map.login "login", :controller => "user_sessions", :action => "new" map.logout "logout", :controller => "user_sessions", :action => "destroy" map.search "search", :controller => "listings", :action => "search" map.edit_my_profile "edit_my_profile", :controller => "users", :action => "edit_my_profile" map.all_listings "all_listings", :controller => "listings", :action => "all_listings" map.my_listings "my_listings", :controller => "listings", :action => "my_listings" map.posting_guidelines "posting_guidelines", :controller => "listings", :action => "posting_guidelines" map.filter_on "filter_on", :controller => "listings", :action => "filter_on" map.top_25_tags "top_25_tags", :controller => "tagging_search", :action => "top_25_tags" map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end

    Read the article

  • Rails routing to XML/JSON without views gone mad

    - by John Schulze
    I have a mystifying problem. In a very simple Ruby app i have three classes: Drivers, Jobs and Vehicles. All three classes only consist of Id and Name. All three classes have the same #index and #show methods and only render in JSON or XML (this is in fact true for all their CRUD methods, they are identical in everything but name). There are no views. For example: def index @drivers= Driver.all respond_to do |format| format.js { render :json => @drivers} format.xml { render :xml => @drivers} end end def show @driver = Driver.find(params[:id]) respond_to do |format| format.js { render :json => @driver} format.xml { render :xml => @driver} end end The models are similarly minimalistic and only contain: class Driver< ActiveRecord::Base validates_presence_of :name end In routes.rb I have: map.resources :drivers map.resources :jobs map.resources :vehicles map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' I can perform POST/create, GET/index and PUT/update on all three classes and GET/read used to work as well until I installed the "has many polymorphs" ActiveRecord plugin and added to environment.rb: require File.join(File.dirname(__FILE__), 'boot') require 'has_many_polymorphs' require 'active_support' Now for two of the three classes I cannot do a read any more. If i go to localhost:3000/drivers they all list nicely in XML but if i go to localhost:3000/drivers/3 I get an error: Processing DriversController#show (for 127.0.0.1 at 2009-06-11 20:34:03) [GET] Parameters: {"id"=>"3"} [4;36;1mDriver Load (0.0ms)[0m [0;1mSELECT * FROM "drivers" WHERE ("drivers"."id" = 3) [0m ActionView::MissingTemplate (Missing template drivers/show.erb in view path app/views): app/controllers/drivers_controller.rb:14:in `show' ...etc This is followed a by another unexpected error: Processing ApplicationController#show (for 127.0.0.1 at 2009-06-11 21:35:52)[GET] Parameters: {"id"=>"3"} NameError (uninitialized constant ApplicationController::AreaAccessDenied): ...etc What is going on here? Why does the same code work for one class but not the other two? Why is it trying to do a #view on the ApplicationController? I found that if I create a simple HTML view for each of the three classes these work fine. To each class I add: format.html # show.html.erb With this in place, going to localhost:3000/drivers/3 renders out the item in HTML and I get no errors in the log. But if attach .xml to the URL it again fails for two of the classes (with the same error message as before) while one will output XML as expected. Even stranger, on the two failing classes, when adding .js to the URL (to trigger JSON rendering) I get the HTML output instead! Is it possible this has something to do with the "has many polymorphs" plugin? I have heard of people having routing issues after installing it. Removing "has many polymorphs" and "active support" from environment.rb (and rebooting the sever) seems to make no difference whatsoever. Yet my problems started after it was installed. I've spent a number of hours on this problem now and am starting to get a little desperate, Google turns up virtually no information which makes me suspect I must have missed something elementary. Any enlightenment or hint gratefully received! JS

    Read the article

  • Using Rails, problem testing has_many relationship

    - by east
    The summary is that I've code that works when manually testing, but isn't doing what I would think it should when trying to build an automated test. Here are the details: I've two models: Payment and PaymentTranscation. class Payment ... has_many :transactions, :class_name => 'PaymentTransaction' class PaymentTranscation ... belongs_to payment The PaymentTransaction is only created in a Payment model method, like so: def pay_up ... transactions.create!(params...) ... end I've manually tested this code, inspected the database, and everything works well. The failing automated test looks like this: def test_pay_up purchase = Payment.new(...) assert purchase.save assert_equal purchase.state, :initialized.to_s assert purchase.pay_up # this should create a new PaymentTransaction... assert_equal purchase.state, :succeeded.to_s assert_equal purchase.transactions.count, 1 # FAILS HERE; transactions is an empty array end If I step through the code, it's clear that the PaymentTransaction is getting created correctly (though I can't see it in the database because everything is in a testing transaction). What I can't figure out is why transactions is returning an empty array in the test when I know a valid PaymentTransaction is getting created. Anybody have some suggestions? Thanks in advance, east

    Read the article

  • Creating a Rails query from a hash of user input

    - by Jamie
    I'm attempting to create a fairly complex search engine for a project using a variable number of search criteria. The user input is sorted into an array of hashes. The hashes contain the following information: { :column => "", :value => "", :operator => "", # Such as: =, !=, <, >, etc. :and_or => "", # Two possible values: "and" and "or" } How can I loop through this array and use the information in these hashes to make an ActiveRecord WHERE query?

    Read the article

  • Tagging in rails with is_taggable

    - by poseid
    there is an example provided on how to add tags to a model with is_taggable, and it works very nice (working in 5 minutes) Now, I also need the opposite, show all records that are tagged with a certain word. Something like: ModelWithTag.find_by_tags "foo" or find_all_tagged_with "foo" Is this possible with is_taggable ?

    Read the article

< Previous Page | 92 93 94 95 96 97 98 99 100 101 102 103  | Next Page >