I am trying to use Capistrano to deploy to two different roles, using Bundler on both, however the Bundler command and flags will be different. Is it possible to set variables that are specific to a role? Either something like:
set :bundle_flags, "--deployment --quiet", :role => "web"
or:
role :web do
set :bundler_cmd, "--deployment --quiet"
end
Neither of those two options work, of course. Is there a way to accomplish this, or something like it?
I've got a model with its validations, and I found out that I can't update an attribute without validating the object before.
I already tried to add on => :create syntax at the end of each validation line, but I got the same results.
My announcement model have the following validations:
validates_presence_of :title
validates_presence_of :description
validates_presence_of :announcement_type_id
validate :validates_publication_date
validate :validates_start_date
validate :validates_start_end_dates
validate :validates_category
validate :validates_province
validates_length_of :title, :in => 6..255, :on => :save
validates_length_of :subtitle, :in => 0..255, :on => :save
validates_length_of :subtitle, :in => 0..255, :on => :save
validates_length_of :place, :in => 0..50, :on => :save
validates_numericality_of :vacants, :greater_than_or_equal_to => 0, :only_integer => true
validates_numericality_of :price, :greater_than_or_equal_to => 0, :only_integer => true
My rake task does the following:
task :announcements_expiration => :environment do
announcements = Announcement.expired
announcements.each do |a|
#Gets the user that owns the announcement
user = User.find(a.user_id)
puts a.title + '...'
a.state = 'deactivated'
if a.update_attributes(:state => a.state)
puts 'state changed to deactivated'
else
a.errors.each do |e|
puts e
end
end
end
This throws all the validation exceptions for that model, in the output.
Does anybody how to update an attribute without validating the model?
I'm using form_for to create a chatroom and when I view the page I get the following error:
NoMethodError in Chatrooms#new
undefined method `chatrooms_path' for #<#<Class:0xa862b94>:0xa5307f0>
Here's the code for the view, located in app/views/chatrooms/new.html.erb:
<div class="center">
<%= form_for(@chatroom) do |f| %>
<%=f.text_field :topic%>
<br>
<%=f.submit "Start a discussion", class: "btn btn-large btn-primary"%>
<% end %>
</div>
Here's the relevant controller:
class ChatroomsController < ApplicationController
def new
@chatroom = Chatroom.new
end
def show
@chatroom = Chatroom.find(params[:id])
end
end
If I change the line
<%= form_for(@chatroom) do |f| %>
to
<%= form_for(:chatroom) do |f| %>
it works fine.
I've searched around for similar questions but none of the solutions have worked for me. Help?
From the list view of my app, I can view a list of records or drill down and edit/update a record. After updating, I want to go directly back to the list view, bypassing a couple of intermediate pages - but I don't simply want to link_to(:action => list) - there's pagination involved. I want to go back to the exact 'list' page I came from. What's the best way? Pass a hidden arg somewhere with the page number? Is there an elegant way to accomplish this?
How can I translate this SQL into a named_scope? Also, I want the total comments param to be passed through a lambda.
"select users., count() as total_comments from users, comments where (users.id = comments.user_id) and (comments.public_comment = 1) and (comments.aasm_state = 'posted') and (comments.forum_user_id is null) group by users.id having total_comments 25"
How can I correctly validate a Visa Debit card in ActiveMerchant?
At the moment, the card fails to validate despite it being a valid card number. I have tried using :visa, :visa_debit and nil card types.
Lets say I have a URL (http://www.example.com/something). Is the following scenario somehow possible?
A) The user visits the URL directly and a standard page with markup, js, etc. is shown.
B) The user embeds the same URL in an image tag and the URL is served only as an image.
I want to create a "Config" class that acts somewhere between a hash and a tree. It's just for storing global values, which can have a context.
Here's how I use it:
Config.get("root.parent.child_b") #=> "value"
Here's what the class might look like:
class Construct
def get(path)
# split path by "."
# search tree for nodes
end
def set(key, value)
# split path by "."
# create tree node if necessary
# set tree value
end
def tree
{
:root => {
:parent => {
:child_a => "value",
:child_b => "another value"
},
:another_parent => {
:something => {
:nesting => "goes on and on"
}
}
}
}
end
end
Is there a name for this kind of thing, somewhere between Hash and Tree (not a Computer Science major)? Basically a hash-like interface to a tree.
Hi there,
I'm trying to run the following spec:
describe UsersController, "GET friends" do
it "should call current_user.friends" do
user = mock_model(User)
user.should_receive(:friends)
UsersController.stub!(:current_user).and_return(user)
get :friends
end
end
My controller looks like this
def friends
@friends = current_user.friends
respond_to do |format|
format.html
end
end
The problem is that I cannot stub the current_user method, as when I run the test, I get:
Spec::Mocks::MockExpectationError in 'UsersController GET friends should call current
_user.friends'
Mock "User_1001" expected :friends with (any args) once, but received it 0 times[0m
./spec/controllers/users_controller_spec.rb:44:
current_user is a method from Restful-authentication, which is included in this controller. How am I supposed to test this controller?
Thanks in advance
I'm refactoring some code and this proc is causing an error randomly and I don't know why or how to debug it... Any ideas?
New code with proc
defense_moves, offense_moves = [], []
determine_move = ->move,side,i { side << move.count(move[i]) }
defense.size.times { |i| determine_move.(defense, defense_moves, i) }
offense.size.times { |i| determine_move.(offense, offense_moves, i) }
dm = defense[defense_moves.index(defense_moves.max)].nil? ? [0] : defense[defense_moves.index(defense_moves.max)]
om = offense[offense_moves.index(offense_moves.max)].nil? ? [0] : offense[offense_moves.index(offense_moves.max)]
Original code:
d = 0
defense_moves = []
loop do
defense_moves << defense.count(defense[d])
break if defense.count(defense[d]).zero?
d += 1
end
o = 0
offense_moves = []
loop do
offense_moves << offense.count(offense[o])
break if offense.count(offense[o]).zero?
o += 1
end
dm = defense[defense_moves.index(defense_moves.max)].nil? ? [0] : defense[defense_moves.index(defense_moves.max)]
om = offense[offense_moves.index(offense_moves.max)].nil? ? [0] : offense[offense_moves.index(offense_moves.max)]
TypeError
ttt2.rb:95:in `[]': no implicit conversion from nil to integer (TypeError)
from ttt2.rb:95:in `computer_make_move'
from ttt2.rb:133:in `draw_board'
from ttt2.rb:24:in `place'
from ttt2.rb:209:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:199:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:199:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:199:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:199:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:234:in `<main>'
My situation is like this.
Company has many users and users may belongs to many companies.
And current implementation is something like below.
class Company
has_many :employments
has_many :users, :through = :employments
end
class Employment
belongs_to :company
belongs_to :user
end
class User
has_many :employments
has_many :companies, :through = :employments #This doesn't looks correct
end
It works, but "user has many companies" doesn't looks logically meaningful. It must be some thing like belongs_to_many companies.
Do I need to use has_and_belongs_to_many?
Can some one please suggest the right way for representing these relationships?
I currently have three methods which I want to collapse into one:
def send_email(contact,email)
end
def make_call(contact, call)
return link_to "Call", new_contact_call_path(:contact => contact, :call => call, :status => 'called')
end
def make_letter(contact, letter)
return link_to "Letter", new_contact_letter_path(:contact => contact, :letter => letter, :status => 'mailed')
end
I want to collapse the three into one so that I can just pass the Model as one of the parameters and it will still correctly create the path_to. I am trying to do this with the following, but stuck:
def do_event(contact, call_or_email_or_letter)
model_name = call_or_email_or_letter.class.name.tableize.singularize
link_to "#{model_name.camelize}", new_contact_#{model_name}_path(contact, call_or_email_or_letter)"
end
Is there an easier way than below to find the longest item in an array?
arr = [
[0,1,2],
[0,1,2,3],
[0,1,2,3,4],
[0,1,2,3]
]
longest_row = []
@rows.each { |row| longest_row = row if row.length > longest_row.length }
p longest_row # => [0,1,2,3,4]
I am trying to test my views with RSpec. The particular view that is causing me troubles changes its appearance depending on a url parameter:
link_to "sort>name", model_path(:sort_by => 'name') which results in http://mydomain/model?sort_by=name
My view then uses this parameter like that:
<% if params[:sort_by] == 'name' %>
<div>Sorted by Name</div>
<% end %>
The RSpec looks like this:
it "should tell the user the attribute for sorting order" do
#Problem: assign params[:sort_for] = 'name'
render "/groups/index.html.erb"
response.should have_tag("div", "Sorted by Name")
end
I would like to test my view (without controller) in RSpec but I can't get this parameter into my params variable. I tried assign in all different flavours:
assign[:params] = {:sort_by => 'name'}
assign[:params][:sort_by] = 'name'
...
no success so far. Every idea is appreciated.
So I came up with the general idea to write some code in JRuby, then access all the classes via Java. I have no idea if this is at all possible but I wanted to ask anyway. Lets say I
have some JRuby code:
class adder
def addme
return 22
end
end
If I compiled this with jrubyc is there any way I could then possibly do something like this in java:
import adder;
class anything {
void testMethod()
{
adder a = new adder();
int x = a.addme();
}
}
After looking at it now it sort of makes me think that Java will have zero idea what sort of item test addme is going to return so that might not work. I don't know but I wanted to throw it out there anyway.
Thanks
Hi there guys! Hope your all enjoying your hollydays.
Ive run into a pretty funny problem when trying to insert rows into a really really simple database table.
The basic idea is pretty simple. The user selects one/multiple users in a multiselect which are supposed to be added to a group.
This piece of code will insert a row into the user_group_relationships table, but the users id always
@group = Group.find(params[:group_id])
params[:newMember][:users].each do |uid|
# For debugging purposes.
puts 'Uid:'+uid
@rel = @group.user_group_relationships.build( :user_id => uid.to_i )
@rel.save
end
The user id always gets inserted as null even though it is clearly there. You can see the uid in this example is 5, so it should work.
Uid:5
...
SQL (0.3ms) INSERT INTO
"user_group_relationships"
("created_at", "group_id",
"updated_at", "user_id") VALUES
('2010-12-27 14:03:24.331303', 2,
'2010-12-27 14:03:24.331303', NULL)
Any ideas why this fails?
My application accepts file uploads, with some metadata being stored in the DB, and the file itself on the file system. I am trying to make the metadata visible in the application before the file upload and post-processing are finished, but because saves are transactional, I have had no success. I have tried the callbacks and calling create_or_update() instead of save(), all to no avail. Is there a way to do this without re-writing the guts of ActiveRecord::Base? I've even attempted naming the method make() instead of save(), but perplexingly that had no effect.
The code below "works" fine, but the database is not modified until everything else is finished.
def save(upload)
uploadFile = upload['datafile']
originalName = uploadFile.original_filename
self.fileType = File.extname(originalName)
create_or_update()
# write the file
File.open(self.filePath, "wb") { |f| f.write(uploadFile.read) }
begin
musicFile = TagLib::File.new(self.filePath())
self.id3Title = musicFile.title
self.id3Artist = musicFile.artist
self.id3Length = musicFile.length
rescue TagLib::BadFile => exc
logger.error("Failed to id track: \n #{exc}")
end
if(self.fileType == '.mp3')
convertToOGG();
end
create_or_update()
end
Any ideas would be quite welcome, thanks.
ferret,multiple model search -
I have 2 models A and B.I want to perform a text search by using 3 fields; title, description(part of A) and comment(part of B). Where I want to include the comment field to perform the ferret search.Then,what other changes needed.
class A < ActiveRecord::Base
has_one :b
acts_as_ferret :fields => [:title, :description],
:additional_fields => [:comment_text]
def comment_text
return b.comment
end
In a_controller, i wrote:
@search = A.find_with_ferret(
params[:st][:text_search],
:limit => :all,
:multi => [B]
).paginate :per_page =>10, :page=>params[:page]
The second mosel is given below:
class B < ActiveRecord::Base
belongs_to :a
while using :multi[B] option with the find_with_ferret,the following error is getting:
undefined method `aaf_index' for #ClassName
I have three models, user, achievement, badge and I plan on using has_many :through instead of has_many_and_belongs_to since I will have a few extra fields in the join tables.
According to a Railscast I watched, using this method requires coming up with new model names and not user_badge or user_achievement.
For my User Achievement join what do you think of Accomplishment?
For my User Badge join what do you think of Distinction?
I let my users create photo albums with many photos. Relationship as follows:
has_many :album_photos, :dependent => :destroy
i upload photos to S3
When the user delete album I want to delete all photos as the relationship shows but it takes time if the user has many photos.
Can I automatically set photo deletion to happen in the background (delayed_job) without having to manually call 'send_later' on every photo?
I have a model called user which has_one email. I put the foreign key (NOT NULL) inside users table.
Now I'm trying to save it in the following way:
@email = Email.new(params[:email])
@email.user = User.new(params[:user])
@email.save
This raises a db exception, because the foreign key constraint is not met (NULL is inserted into email_id). How can I elegantly solve this or is my data modeling wrong?
Hi I have a tree structure.. I am using Awesome nested set plugin. how to add nodes to the children at various levels. Please help me. I want to add ,edit and delete nodes at any levels.
Can anyone help me for the same?
I have an aggregated attribute which I want to be able ask about its _changed? ness, etc.
composed_of :range,
:class_name => 'Range',
:mapping => [ %w(range_begin begin), %w(range_end end)],
:allow_nil => true
If I use the aggregation:
foo.range = 1..10
This is what I get:
foo.range # => 1..10
foo.range_changed? # NoMethodError
foo.range_was # ditto
foo.changed # ['range_begin', 'range_end']
So basically, I'm not getting ActiveRecord::Dirty semanitcs on aggregated attributes. Is there any way to do that? I'm not having a lot of luck with alias_attribute_with_dirty, etc.