this is what I have in my view:
<% form_remote_tag :url => { :controller => 'comments', :action => "create", :post_id => "#{@post.id}"}, :html => {:id => 'comment_form' },
:before => "tinyMCE.triggerSave(true,true);" do %>
<%= label_tag 'Comment' %><br/>
<%= text_area_tag :comment_body, nil,:rows => 10, :cols => 100 %><br/>
<p style="margin-top: 10px;">
<%= submit_tag 'Add',:id => 'btnCommentSave' %>
</p>
<% end %>
Tinymce editor is displayed properly.
In my controller:
how to get the contents of the text area?
I am expecting the contents in params[:comment_body] and I am not seeing it?
I tried doing this also,
$('#btnCommentSave').click( function(){
tinyMCE.triggerSave(true,true);
$('#comment_form').submit();
});
What am I missing?
Thanks
Hello,
I'm trying to prevent a record that has a relationship to another record from being deleted. I can stop the deletion but not send a flash message as I had hoped!
class Purchaseitem < ActiveRecord::Base
before_destroy :check_if_ingredient
...
def check_if_ingredient
i = Ingredient.find(:all, :conditions => "purchaseitem_id = #{self.id}")
if i.length > 0
self.errors.add(:name)
flash.now[:notice] =
"#{self.name} is in use as an ingredient and cannot be deleted"
return false
end
end
This will prevent a the delete wihthout the flash line, and when I add it I get:
undefined local variable or method `flash' for #
Any help would be much appreciated!
Hi I have a post model that :has_many :reply, when using searchlogic, doing Post.reply_content_like("search"), returns a result for every reply under that post, I only want it to return once. Anyone know a way to solve this
Hi folks, I have a function that is being called more than a thousand times, slowing everything down. However, it is a low level function, and do not know which of my high level function is lopping and making these calls. How can i find out?
Hello
I'm confuse about objects that I can't save, simplified model is
class Subscription < ActiveRecord::base
belongs_to :user, :class_name => "User", :foreign_key => "user_id"
has_many :transactions, :class_name => "SubscriptionTransaction"
validates_presence_of :first_name, :message => "ne peut être vide"
validates_presence_of :last_name, :message => "ne peut être vide"
validates_presence_of :card_number, :message => "ne peut être vide"
validates_presence_of :card_verification, :message => "ne peut être vide"
validates_presence_of :card_type, :message => "ne peut être vide"
validates_presence_of :card_expires_on, :message => "ne peut être vide"
attr_accessor :card_number, :card_verification
validate_on_create :validate_card
def validate_card
unless credit_card.valid?
credit_card.errors.full_messages.each do |message|
errors.add_to_base message
end
end
end
def credit_card
@credit_card ||= ActiveMerchant::Billing::CreditCard.new(
:type => card_type,
:number => card_number,
:verification_value => card_verification,
:month => card_expires_on.month,
:year => card_expires_on.year,
:first_name => first_name,
:last_name => last_name
)
end
end
and in my subscription_controller
if subscription.save
# do something
else
debugger # means breakpoint where i try subscription.errors.full_messages
# do something else
end
I tried to use ruby-debug for this adding a breakpoint before. And subscription.valid? return false which explains that ActiveRecord doesn't allow the save method. Unfortunately i can't know why the object is invalid.
subscription.errors.full_messages # => []
I'm stucked, if you have any idea, thank you.
Hey,Guys!
Now I hava a problem,how can I make the callback#after_add receive a reference to the join model in a has_many :through association?
my code like this:
class Emergency
has_many :departments, :through => :eme_references, :after_add => Proc.new { |eme_reference| eme_reference.eme_flag = 1}
end
the attribute eme_flag is the model EmeReference's attribute! but in the block ,i get the eme_reference.class is Emergency.
I want to set the attribute eme_flag of the model EmeReference.
That is my question!
cheers!
When building the following factory:
Factory.define :user do |f|
f.sequence(:name) { |n| "foo#{n}" }
f.resume_type_id { ResumeType.first.id }
end
ResumeType.first returns nil and I get an error.
ResumeType records are loaded via fixtures. I checked using the console and the entries are there, the table is not empty.
I've found a similar example in the factory_girl mailing list, and it's supposed to work.
What am I missing? Do I have to somehow tell factory_girl to set up the fixtures before running the tests?
I have a form in one controller(A) that renders a partial from another controller(B), and stays on A's edit page during editing / updating etc.
However... When the partial form form controller B has an error, the error doesn't show up on A's edit page
right now, if there is an error, I am doing (in controller B's update method)
redirect_to :controller => "A", :action => "edit"
and then this is built in... but I don't know what to do with it... the error needs to be sent to controller A... but.. it doesn't
format.xml { render :xml => @varFromB.errors, :status => :unprocessable_entity }
thanks
Currently I have two versions of rack installed on my computer 1.0.1 and 1.2.1
However, when I tried to push my git to Heroku, it complains
You have already activated rack 1.0.1, but your Gemfile requires rack 1.2.1. Consider using bundle exec. (Gem::LoadError)
How can I deactivate rack 1.0.1 and activate 1.2.1 instead? (I can't uninstall 1.0.1 since it's under system folder and I don't have the root password)
Hello, I didn't exactly know how to pose this question other than through example...
I have a class we will call Foo. Foo :has_many Bar. Foo has a boolean attribute called randomize that determines the order of the the Bars in the :has_many relationship:
class CreateFoo < ActiveRecord::Migration
def self.up
create_table :foos do |t|
t.string :name
t.boolean :randomize, :default => false
end
end
end
class CreateBar < ActiveRecord::Migration
def self.up
create_table :bars do |t|
t.string :name
t.references :foo
end
end
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
class Foo < ActiveRecord::Base
# this is the line that doesn't work
has_many :bars, :order => self.randomize ? 'RAND()' : 'id'
end
How do I access properties of self in the has_many declaration?
Things I've tried and failed:
creating a method of Foo that returns the correct string
creating a lambda function
crying
Is this possible?
UPDATE
The problem seems to be that the class in :has_many ISN'T of type Foo:
undefined method `randomize' for #<Class:0x1076fbf78>
is one of the errors I get. Note that its a general Class, not a Foo object... Why??
I am playing with custom view and routes. I think that I have everything right but obviously not. Essentially I tried to copy the show method and show.html.erb but for some reason it will not work.
My controller
class fatherController < ApplicationController
def show
@father = Father.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @father }
end
end
def ofmine
@father = Father.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @father }
end
end
end
My routes.rb
Parent::Application.routes.draw do
resources :fathers do
resources :kids
end
match 'hospitals/:id/ofmine' => 'father#show2'
end
when I go to
127.0.0.1:/father/1
it works fine but when I try to go to
127.0.0.1:/father/1/ofmine
it gives the following error. It doesn't matter what the variable/method that is called; it occurs at the first one to be displayed. Both show.html.erb and show2.html.erb are the exact same files
My Error from webserver commandline
> Processing by fathersController#show2
> as HTML Parameters: {"id"=>"1"}
> Rendered fathers/show2.html.erb within
> layouts/application (31.6ms) Completed
> in 37ms
>
> ActionView::Template::Error (undefined
> method `name' for nil:NilClass):
> 4: <td>Name</td><td></td>
> 5: </tr>
> 6: <tr>
> 7: <td><%= @father.name %></td><td></td>
> 8: </tr>
> 9: <tr>
> 10: <td>City</td><td>State</td> app/views/fathers/show2.html.erb:7:in
> `_app_views_fatherss_show__html_erb___709193087__616989688_0'
Error as displayed on actual page
NoMethodError in Fathers#show2
Showing
/var/ruby/chs/app/views/fathers/show2.html.erb
where line #7 raised:
undefined method `name' for
nil:NilClass
Extracted source (around line #7):
4: Name 5:
6: 7: <%=
@father.name % 8:
9: 10:
CityState
If anyone could tell me what in the world I am doing wrong I would appreciate it greatly.
I use Ultrasphinx gem plugin as a wrapper for accessing Sphinx search daemon.
My model declaration:
class Foo < ActiveRecord::Base
is_indexed :fields => ['content', 'private_notes', 'user_id']
Client code:
filters = {}
if type == "private"
# search only in `content` column
filters['user_id'] = current_user.id
else
# search in `content` and `private_notes` columns
end
results = Ultrasphinx::Search.new(:query => params[:query],
:per_page => 20,
:page => params[:page] || 1,
:filters => filters)
The problem I have now with Ultrasphinx gem(or Sphinx, in general?) is that it does not allow me to change set of fields where to look for matches IN RUNTIME
How can I solve this problem?
What is the best way to set default value in ActiveRecord?
I see a post from Pratik that describes an ugly, complicated chunk of code: http://m.onkey.org/2007/7/24/how-to-set-default-values-in-your-model
class Item < ActiveRecord::Base
def initialize_with_defaults(attrs = nil, &block)
initialize_without_defaults(attrs) do
setter = lambda { |key, value| self.send("#{key.to_s}=", value) unless
!attrs.nil? && attrs.keys.map(&:to_s).include?(key.to_s) }
setter.call('scheduler_type', 'hotseat')
yield self if block_given?
end
end
alias_method_chain :initialize, :defaults
end
YUCK!
I have seen the following examples googling around:
def initialize
super
self.status = ACTIVE unless self.status
end
and
def after_initialize
return unless new_record?
self.status = ACTIVE
end
I've also seen people put it in their migration, but I'd rather see it defined in the model code.
What's the best way to set default value for fields in ActiveRecord model?
thanks for your time first...after all the searching on google, github and here, and got more confused about the big words(partition/shard/fedorate),I figure that I have to describe the specific problem I met and ask around.
My company's databases deals with massive users and orders, so we split databases and tables in various ways, some are described below:
way database and table name shard by (maybe it's should be called partitioned by?)
YZ.X db_YZ.tb_X order serial number last three digits
YYYYMMDD. db_YYYYMMDD.tb date
YYYYMM.DD db_YYYYMM.tb_ DD date too
The basic concept is that databases and tables are seperated acording to a field(not nessissarily the primary key), and there are too many databases and too many tables, so that writing or magically generate one database.yml config for each database and one model for each table isn't possible or at least not the best solution.
I looked into drnic's magic solutions, and datafabric, and even the source code of active record, maybe I could use ERB to generate database.yml and do database connection in around filter, and maybe I could use named_scope to dynamically decide the table name for find, but update/create opertions are bounded to "self.class.quoted_table_name" so that I couldn't easily get my problem solved. And even I could generate one model for each table, because its amount is up to 30 most.
But this is just not DRY!
What I need is a clean solution like the following DSL:
class Order < ActiveRecord::Base
shard_by :order_serialno do |key|
[get_db_config_by(key), #because some or all of the databaes might share the same machine in a regular way or can be configed by a hash of regex, and it can also be a const
get_db_name_by(key),
get_tb_name_by(key),
]
end
end
Can anybody enlight me? Any help would be greatly appreciated~~~~
I have a script file for parsing through a SQLite database. I now need to create a CRON job that will download and unzip said database from a third-party (already hosting as SQLITE). I understand this can be done using WGET and UNZIP, but given Heroku's read only file system, is this possible entirely in memory? Thanks.
Hey,Guys!
Now I hava a problem,how can I make the callback#after_add receive a reference to the join model in a has_many :through association?
my code like this:
class Emergency
has_many :departments, :through => :eme_references, :source => :email, :after_add => Proc.new { |eme_reference| eme_reference.eme_flag = 1}
end
the attribute eme_flag is the model EmeReference's attribute! but in the block ,i get the eme_reference.class is Emergency.
I want to set the attribute eme_flag of the model EmeReference.
That is my question!
cheers!
Is there a way to pre-populate a user's documents list with server-generated log files? A way to offer any files at a given path? Is this a job for plugins or native to some settings config?
thx
Now I know how to build xml without escaping values. http://stackoverflow.com/questions/2693036/how-to-tell-bulider-to-not-to-escape-values
However I need to build tags dynamically.
Desired result
<bank_info>Chase</bank_info>
What I have is
attr = 'bank_info'
builder = Builder::XmlMarkup.new
builder.attr { |x| x << 'bank_info' } # does not work
I can try making the whole thing as a giant string and eval that. But evaling is not that safe. Is there a better option that I am missing.
I have a Model Campaign.
A Campaign has many Events.
Each Event has an attribute :days.
A Campaign also has_many Contacts.
Each Contact as a :date_entered attribute.
The from_today(contact,event) method returns a number, which is the number of days from the contact's :date_entered till today minus the event's :days. In other words, a positive number shows the number of days from today till the :days of the event is elapsed. If it is negative, if means that the number of days that has elapsed since the :date_entered is greater than the :days attribute of an event. In other words, the event is overdue.
What I would like to be able to do is do campaign.overdue and this would result in a total number of contacts that have an overdue event. It shouldn't count multiple events for a single contact, just one contact.
How do I do that? It seems like I would need to cycle through all the events for every contact and keep a counter but I'm assuming that there is a better way.
Im trying to get a controller to create a new account with the user id filled in, this doesn't work in my controller or in the console, why? Any suggestions on how to implement this would be much appreciated.
class PaymentNotification < ActiveRecord::Base
after_create :add_account_to_market
private
def add_account_to_market
if status == "Completed"
line = LineItem.find(:first, :conditions => { :cart_id => cart.id })
line.quantity.times do
Account.new(:user_id => cart.user_id)
end
end
end
end
Hello:
I have a note table with columns:
title :string
content :text
rating :integer
and a thinking_sphinx configuration:
define_index do
indexes :title, :sortable => true
indexes :content
end
Then I can search the notes and assign weights to title and content to define the order or the result:
Note.search "abc", :match_mode => :extended, :field_weights => {
:title => 10,
:content => 3
}
Now I want to assign a weight to the rating column
The type of the rating column is integer. The range of the rating is [1, 2, 3, 4, 5].
Can I just add weight at the :field_weights
:field_weights => {
:title => 10,
:content => 3,
:rating => 5
}
or I need to do something else to make the note which has higer rating display first?
This is my code:
[email protected] do |a|
-if @i%3 == 0
%ul
%li=link_to a.name, a
-@i += 1
I need the li to be inside the ul which is inside the if-statement.
I can't do it because of the indentation. Can't I just tell the li to indent automatically?
Thanks
I'm getting the following error:
Unknown action
No action responded to show. Actions: activate, destroy, index, org_deals, search, and suspend
Controller:
class Admin::HomepagesController < Admin::ApplicationController
def org_deals
@organization = Organization.find(:all)
end
Routes:
admin.resources :organizations, :collection => {:search => :get}, :member => {:suspend => :get, :activate => :get}
To note: This is a controller inside of a controller.
Any ideas why this is?