Rails - One-direction table association - accessing data issue - ruby-on-rails

I have two models:
class Order < ActiveRecord::Base
belongs_to :user
has_one :order_type
end
class OrderType < ActiveRecord::Base
belongs_to :order
end
my schema.rb:
create_table "order_types", force: :cascade do |t|
t.string "ort_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "orders", force: :cascade do |t|
t.string "ord_name"
t.date "ord_due_date"
t.integer "user_id"
t.integer "ordertype_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "orders", ["ordertype_id"], name: "index_orders_on_ordertype_id"
add_index "orders", ["user_id"], name: "index_orders_on_user_id"
There is only one-direction association between them. The Order model has a column "ordertype_id" that links to the appropriate order_type.
My question is, what is the best practice to access the ort_name value for each #order in a view.
Currently, I am using:
<p>
<strong>Ord type:</strong>
<% OrderType.where(id: #order.ordertype_id).each do |t| %>
<%= t.ort_name %>
<% end %>
</p>
This solution results in many code repetitions. How I should change that? Can somebody advise, as I am not so experienced yet?
I tried this code, but it did not work:
#orders.order_type

There are many problems which you should address. It's ok to be a beginner, just take yourself time to learn and improve.
Schema
First off, your schema is set up badly. If you want to limit the order type to certain values, you should do this with a validation.
class Order
TYPES = %w[foo bar three four five]
validates :order_type, inclusion: { in: TYPES }
end
This way, you can easily add values in the future, and remove the complexity of adding a new model and its relations.
Column Names
Secondly, you should revise your column names. ord_name and ord_due_date is bad, it leads to ugly calls like order.ord_name. You should drop the prefix ord, it's superfluous.
Both steps would lead to this schema.rb
create_table "orders", force: :cascade do |t|
t.string "name"
t.date "due_date"
t.integer "user_id"
t.string "order_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Logic placement
My final advice is to never call queries from your view. Logic should always be in the controller / model & passed to the view via instance variables.
This is a big no no in rails:
<% OrderType.where(id: #order.ordertype_id).each do |t| %>
...
<% end %>
In the end, accessing the type is simply accomplished with:
#order.order_type

Update your Order model to this:
class Order < ActiveRecord::Base
belongs_to :user
has_one :order_type, foreign_key: 'ordertype_id`
end
then order_type should be easily accessible:
#order.order_type.ort_name

Related

Multiple Checkbox in Ruby

I'm trying to create an "ingredient" checkbox list derived from my "recipes", I'd like for the values to be saved in the database so that when it's checked and I refresh the page, it still shows as checked.
The error says "uninitialized constant #Class:0x00007f8f2d360830::Parties"
Here's an example of what i am trying to do
Controller:
# parties_controller.rb
def ingredients
#party = Party.find(params[:party_id])
#party_recipe = #party.recipes
#party_recipe.each do |recipe|
#ingredients = recipe.ingredients
end
The models:
Party model
#party.rb
class Party < ApplicationRecord
has_many :party_recipes
has_many :recipes, through: :party_recipes
end
Recipe model
#recipe_ingredient.rb
class RecipeIngredient < ApplicationRecord
belongs_to :recipe
belongs_to :ingredient
end
Ingredient model
#ingredient.rb
class Ingredient < ApplicationRecord
has_many :recipe_ingredients
has_many :recipes, through: :recipe_ingredients
end
Form:
#ingredients.html.erb
<% form_for "/parties/#{#party.id}/ingredients" do |f| %>
<% Parties::Recipes::Ingredients.each do |ingredient| %>
<%= check_box_tag(ingredient) %>
<%= ingredient %>
<% end %>
<% end %>
Schema:
create_table "ingredients", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "parties", force: :cascade do |t|
t.string "title"
t.string "address"
t.bigint "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "theme"
t.date "date"
t.integer "attendancy"
t.integer "appetizers"
t.integer "mains"
t.integer "desserts"
t.string "status", default: "pending"
t.index ["user_id"], name: "index_parties_on_user_id"
end
create_table "party_recipes", force: :cascade do |t|
t.bigint "recipe_id", null: false
t.bigint "party_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["party_id"], name: "index_party_recipes_on_party_id"
t.index ["recipe_id"], name: "index_party_recipes_on_recipe_id"
end
create_table "recipe_ingredients", force: :cascade do |t|
t.bigint "recipe_id", null: false
t.bigint "ingredient_id", null: false
t.string "amount"
t.boolean "included", default: false
t.index ["ingredient_id"], name: "index_recipe_ingredients_on_ingredient_id"
t.index ["recipe_id"], name: "index_recipe_ingredients_on_recipe_id"
end
create_table "recipes", force: :cascade do |t|
t.string "title"
t.text "description"
end
add_foreign_key "party_recipes", "parties"
add_foreign_key "party_recipes", "recipes"
add_foreign_key "recipe_ingredients", "ingredients"
add_foreign_key "recipe_ingredients", "recipes"
I'm not entirely sure where exactly needs to be corrected, any help appreciated, thank you so much!
Well the error message is correct, you don't have any model called Parties, in fact in Rails, models are always singular, camel-case. So that explains the error message.
However that won't fix your problem! The iterator in the view should be
<% #ingredients.each do |ingredient| %>
<%= check_box_tag(ingredient) %>
<%= ingredient %>
<% end %>
Because I think you are trying to populate an #ingredients variable in your controller. However it still won't work, b/c the value of the #ingredients variable is not being correctly assigned...
Personally I much prefer the "fat model skinny controller" design style for Rails. So I would have a PartiesController#ingredients method that looks like this:
# parties_controller.rb
def ingredients
#party = Party.find(params[:party_id])
#ingredients = #party.ingredients
end
then in your Party model:
# app/models/party.rb
def ingredients
recipes.map(&:ingredients).flatten
end
Why do it this way? Well you're just getting started with Rails, but eventually (soon hopefully) you'll be writing tests, and it's much much easier to write tests on models than controllers.
Now, there could well be some other issues in your code, but try my suggestions and see where that gets you.
#Les Nightingill's answer should work well for organizing your controller and model! Regarding when you click refresh and the value of the boxes are saved either;
Set up some listeners in javascript and send a request to your update controller method every time there is a value change for one of your check boxes.
Or add a save button at the bottom of your form that points to your update controller method to save the values of the checkboxes. Something like:
<%= submit_tag "Save", data: { disable_with: "Saving..." } %>
https://api.rubyonrails.org/v5.2.3/classes/ActionView/Helpers/FormTagHelper.html#method-i-submit_tag

accepts_nested_attributes - ActiveRecord::UnknownAttributeError

I have a very simple model that each event has many forexes. I am trying to create a nested form to create new event with a bunch of forexes in a go.
class Event < ActiveRecord::Base
has_many :forexes
accepts_nested_attributes_for :forexes
end
class Forex < ActiveRecord::Base
belongs_to :event
end
The schema is like this:
ActiveRecord::Schema.define(version: 20180505093823) do
create_table "events", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "base"
end
create_table "forexes", force: :cascade do |t|
t.string "code"
t.float "rate"
t.integer "event_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "forexes", ["event_id"], name: "index_forexes_on_event_id"
end
And then I tried to create new objects using the following code in rails console. It fails.
Event.new( name: "11", base: "HKD", forexes_attributes: [ {code: "RMB", rate:1}, {code: "CNY",rate:2}])
It throws me back with this error.
ActiveRecord::UnknownAttributeError: unknown attribute 'forexes_attributes' for Event.
I know this is quite a basic question. And I have tried many different ways after researching in different places. I couldn't debug it. Appreciate your help.
In your Event controller you need to include the forexes_attributes in event_params method as along with default one
def event_params
params.require(:event).permit(forexes_attributes: Forexes_attribute_names.map(&:to_sym).push(:_destroy))
end

Ransack: Conditions on both a child, and its respective grandchild record

Don't be intimidated by the length. It's probably actually quite simple.I couldn't find an answer, though I tried looking everywhere. I hope this is a good enough challenge for you.
Here goes:
Panel.rb
has_many :status_dates
has_many :statuses, through: :status_dates
StatusDate.rb
belongs_to :status
belongs_to :panel
def self.ransackable_attributes(auth_object = nil)
%w( current ) + _ransackers.keys
end
Status.rb
has_many :status_dates
Here is the schema.
create_table "panels", force: :cascade do |t|
t.string "no"
t.integer "project_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "status_dates", force: :cascade do |t|
t.integer "status_id"
t.integer "panel_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.date "date"
t.boolean "current"
end
add_index "status_dates", ["panel_id"], name: "index_status_dates_on_panel_id"
add_index "status_dates", ["status_id"], name: "index_status_dates_on_status_id"
create_table "statuses", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
What do I want to do?
I want to identify a parent record based on two conditions which must both simultaneously exist exist on: (i) a child record and (ii) in turn, that child's, child record too (i.e. a grand child record).
What does that mean?
Suppose we have:
I want to find all panels, where there is a particular StatusDate record such that StatusDate.current = y, and its respective child, Status.name = x.
(“Current” is actually a boolean value on the StatusDate record.)
What is happening at the moment?
Here is my _condition_fields.html.erb partial:
What is the problem?
Right now, ransack applies those conditions across different records. But I want them applied directly to: (I) a child record and (ii) that particular child's child record as well.
Any idea how I can do this?
Assistance very much appreciated.
Did you try query following way:
Panel.ransack({StatusDate_current:0, StatusDate_Status_name: "Installed"})

I wanna use model attribute in view Rails

I am trying to use attribute value in model but its not working..
I have three models:
models/resident.rb
class Resident < ActiveRecord::Base
belongs_to :hostel
has_one :user,dependent: :delete
end
models/user.rb
class User < ActiveRecord::Base
belongs_to:resident
end
models/hostel.rb
class Hostel < ActiveRecord::Base
has_many :residents
has_one :rate_card,dependent: :delete
end
Schema
Resident
create_table "residents", force: :cascade do |t|
t.string "room_number"
t.string "roll_number"
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "hostel_id"
end
User
create_table "users", force: :cascade do |t|
t.string "roll_number"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "resident_id"
end
Hostel
create_table "hostels", force: :cascade do |t|
t.string "hostel"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Now i want to use the hostel attribute value in users/show.html.erb
I am able to do this :
<%if #user.resident.roll_number=="101303110"%>
if the roll number is present then returning true..
but if is use :
<%if #user.resident.hostel=="J"%>
and if J is a hostel present in Hostel model then it is returning false.
But when we put<%#user.resident.hostel%> in show.html.erb then it is showing value J.
How should I use related models attributes in each other view?
Given your associations, #user.resident.hostel would load a hostel. But you want to compare the hostel string on the hostel. Therefore your comparison should be:
<% if #user.resident.hostel.hostel == 'J' %>
Explanation:
#user # returns your a user
#user.resident # follows `belongs_to :resident` and
# returns a resident
#user.resident.hostel # follows `belongs_to :hostel` on the resident and
# returns a hostel
#user.resident.hostel.hostel # returns the value store in the `hostel`
# column of that `hostel`
Btw. I would argue that chaining calls like that violates the Law of Demeter. But it is hard to suggest any alternative without having more insights into your app.

How do I build a complex nested form to represent dynamic attributes

I've got a data model represented by the following image:
Basically, the idea is that there are many different Collections. All the Items in a single collection will have the same Attributes, but the list of attributes will be different per collection. The value of each Attribute per item will be stored in Item Attribute Values.
I'm trying to build a single page where a user can populate the attributes for an item. I'm assuming a nested form is the way to go but I'm at a loss as to how to represent this in the controller and on the page, considering the names of the attributes are in one table and the values in another.
If anyone has encountered or had to deal with a similar situation, any help would be appreciated.
Thanks
Here is one potential solution.
class Collection
has_and_belongs_to_many :items
has_and_belongs_to_many :attributes
end
class Item
has_and_belongs_to_many :collections
has_many :item_attributes
has_many :attributes, though: :item_attributes
end
class Attributes
has_and_belongs_to_many :collections
has_many :item_attributes
has_many :items, though: :item_attributes
end
class ItemAttribute
belongs_to :item
belongs_to :attribute
end
So lets look at the database layout to back these models:
ActiveRecord::Schema.define(version: 20151027173337) do
create_table "attributes_collections", id: false, force: :cascade do |t|
t.integer "attribute_id", null: false
t.integer "collection_id", null: false
end
create_table "collections", force: :cascade do |t|
t.string "title"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "collections", ["user_id"], name: "index_collections_on_user_id"
create_table "collections_items", id: false, force: :cascade do |t|
t.integer "collection_id", null: false
t.integer "item_id", null: false
end
create_table "item_attributes", force: :cascade do |t|
t.integer "item_id"
t.integer "attribute_id"
t.string "value"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "item_attributes", ["attribute_id"], name: "index_item_attributes_on_attribute_id"
add_index "item_attributes", ["item_id"], name: "index_item_attributes_on_item_id"
create_table "items", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
A Better way?
But of course performance will suffer due to the many joins. Plus each attribute will be stored as a VARCHAR which means you can't do any numeric comparisons in the database.
If you really need a flexible schema i would instead look into using HSTORE, JSON or another dynamic column type or a schemaless database such as MongoDB.
How do I create a form / controller for this?
First you should get very acquainted with what can be done with accepts_nested_attributes_for and fields_for and maybe consider using AJAX to delegate the actions out to CollectionController and a ItemController on the back end rather than cramming it all into a single monstrosity.

Resources