change_column migration deletes table - ruby-on-rails-4

I've run a change_column migration a couple times now and it deletes the entire table I'm trying to make the change to.
class ChangePictureColumnInProperties < ActiveRecord::Migration
def change
change_column :properties, :pictures, :json
end
end
It then just completely deletes the entire properties table.
I'm trying to set-up CarrierWave and the documentation says to "Add a Column that can store an array" and provides an example using JSON, to provide context on what I'm doing.
I'm new to Rails so no clue what I'm doing wrong here. Appreciate any thoughts.

If you are using SQLite you need drop the table and create it again, SQLite doesn't support delete, change type and rename columns (without delete the entry).
In your migration, can do:
drop_table :properties
create_table :properties
add_column :properties, :your_previous_columns
add_column :properties, :your_previous_columns
add_column :properties, :pictures, :json
If you have relevant information, can create another table with the good structure, import your information and after delete the old table.
IMPORTANT!
I don't believe that a json field would be the best option, you can use a "one to many" relationship between your entry and his images.
And when you need add images for you entry use "nested forms".
with nested forms you can send the information that belongs to your entry and his nested images.

Related

Rails 4: strong_params,nested_attributes_for and belongs_to association trouble

I really can't get my head around Rails 4 strong parameters, belongs_to association and form with fields_for.
Imagine I have model for quoting some price:
class Quote < ActiveRecord::Base
belongs_to :fee
accepts_nested_attributes_for :fee
Now, I have seeded some fees into the db, and have put some radiobuttons on my form_for #quote using fields_for. The values of the radiobuttons are simply ids of the records.
Here is the troubling part, the controller:
def create
#quote = Quote.new(quote_params)
...
end
def quote_params
params.require(:quote).permit(:amount_from, fee_attributes: [:id])
end
From my understanding, automagically Rails should fetch fee record with some id, but there is some mystic error instead.
params hash is: "quote"=>{"amount_from"=>"1200", "fee_attributes"=>{"id"=>"1"}}
Log tail:
Completed 404 Not Found in 264ms
ActiveRecord::RecordNotFound (Couldn't find Fee with ID=1 for Quote with ID=)
app/controllers/quotes_controller.rb:14:in `create'
I really don't understand what is going on here, have read Rails association guide, googled for hour for all info, but to no avail.
What I want to achieve here is to understand the correct "Rails way" to fetch some associations for new Quote object using some params I've put in the form.
Guess I got nested_attributes_for wrong, somehow thought it would call Fee.find automagically.
I've opted for ditching fields_for helpers from the form and rendering fields manually like
radio_button_tag 'fee[id]', fee.id
Then in controller I have 2 params methods now:
def quote_params
params.require(:quote).permit(:amount_from)
end
def fee_params
params.require(:fee).permit(:id)
end
And my action looks like
def create
#quote = Quote.new(quote_params)
#quote.fee = Fee.find(fee_params[:id])
...
Any additions on best practices when one has to handle lots of different objects with not so straight init logic are welcome.

Best way to populate a new attribute (new database column) of existing Rails models?

I've just added a new column to an existing table in my database:
class AddMoveableDateToDocument < ActiveRecord::Migration
def change
add_column :documents, :moveable_date, :datetime
end
end
In my Rails model I want the moveable_date attribute to be set to a default value upon creation, and the application will be able to change this date later. So, something like:
class Document < ActiveRecord::Base
before_create :set_moveable_date
def set_moveable_date
self.moveable_date ||= self.created_at
end
end
Now, the existing models that are already saved into the database will not have this moveable_date set yet (the value is nil). How do I run through all my existing models and populate the moveable_date attribute with its default value? What is the easiest/best practice way? Can be in the application code itself, in the console, in the terminal, or otherwise. Thanks!
You will get a lot of opinionated answers on this one. Some will suggest the console, some will suggest a one-time rake task.
I would suggest doing it as part of the migration that adds the column. After adding the column, you can run Document.reset_column_information so that the Rails app picks up on your new column, and then iterate through the existing document records and set the moveable date as appropriate.
Or if it's as simple as setting the moveable date to the created_at date, you can use something like Document.update_all("moveable_date = created_at") instead of iterating over them.
That's a good suggestion!
Another way is to add the line before_save :set_moveable_date to your model. It won't accomplish the transition immediately, but if your data is updated on a regular basis, it'd work.

Rails 4 - Column exists but does not update

I have recently added a field "tag" to my blog app built in Rails 4. Below you can see the field appearing in the Edit view:
But once I return to the Show view after editing, this does not appear:
When I check the database directly I can definitely see it exists:
sqlite> PRAGMA table_info(POSTS);
0|id|INTEGER|1||1
1|title|varchar(255)|0||0
2|body|text|0||0
3|created_at|datetime|0||0
4|updated_at|datetime|0||0
5|slug|varchar(255)|0||0
6|tag|varchar(255)|0||0
Can anyone suggest what is going on or how to troubleshoot this?
Rails 4 uses strong parameters by default. This means you have to explicitly whitelist params you wish to mass assign.
When adding a new attribute to a model, you have to remember to update the permitted params in you controller.
For example, in your case, you would need to make sure :tags are added like so:
class PostController < ActionController::Base
def update
post = Post.find(params[:id])
post.update(post_params)
redirect_to post
end
private
def post_params
params.require(:post).permit(:title, :body, :tag)
end
end

Rails: Invalid single-table inheritance type error

So, I am working on migrating this php site with an existing database which I cannot change over to Rails. There is a table: Quotes with a column named type. Whenever I try and create a model of this and set the type, it tells me the following error:
ActiveRecord::SubclassNotFound (Invalid single-table inheritance type: HOME is not a subclass of Quotes)
I don't understand why it thinks its inheriting because it's not supposed to. My create method looks like this:
quote = Quotes.create(
agent_id: agent.id,
client_id: client.id,
type: 'HOME',
status: 0,
date_created: DateTime.now
)
If I comment out the type, everything works fine. But with the Type it errors.
I resolved this by setting the models inheritance_column to nil. Active Record Models can inherit from a table through the attribute :type, setting the inheritance_column to nil removes that attribute allowing you to have a database column named type
class Quote < ActiveRecord::Base
self.inheritance_column = nil
end
I hate having potential gotchas deep in the code especially in the intial processes like generating a model. Better to just change the reserved word to something else and free yourself up to take advantage of inheritance column later if the need comes up. A cleaner solution is listed here -> rename a database column name using migration
It reads;
Execute $> rails generate migration ChangeColumnName
where, ChangeColumnName is the name of our migration. This can be any name.
Now, edit the generated migration file at db/migrate/_change_column_name.rb
class ChangeColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
$> rake db:migrate
You will have to edit controller and view files e.g. if the model name is Product then you will likely edit these files
/app/views/products/_form.html.erb
/app/views/products/show.html.erb
/app/controllers/products_controller.erb
/app/views/products/index.html.erb

RailsAdmin papertrail empty history

I have configured RailsAdmin to use papertrail for showing the history of changes on models.
It seems to be working fine, but in the UI it displays changes always as an empty array. Is this the expected output? I was expecting to see the actual changes made on the records, or even better a drill down with a before and after change on the record.
Rails 4, RailsAdmin 0.5, PaperTrail 2.7.2
You need to have a column called object_changesin your versions table.
See these instructions from paper_trail. Look at the section called "Diffing Versions."
In short, when you generate the versions table, do this rails g paper_trail:install --with-changes
Or, if you already have an objects table, do this migration:
class AddObjectChangesColumnToVersions < ActiveRecord::Migration
def self.up
add_column :versions, :object_changes, :text
end
def self.down
remove_column :versions, :object_changes
end
end
I'm seeing the exact same thing and filed a bug report with rails_admin: https://github.com/sferik/rails_admin/issues/1751
If that is addressed I'll update this comment.