Accessing attributes from different associated models rails 3 - ruby-on-rails-3

I am looking to get a better understanding of Active Model/Record relationships and how to call attributes dependent upon where the attributes are located (models) and where I am calling them. So for example I can access the attribute dish_name from within the recipe controller like so
def all_recipes
#recipes = Recipe.all
end
In the view
<% #recipes.each do |r| %>
<%= r.dish_name %>
<% end %>
Now say i want to access a recipe attribute from within my controller called worldrecipes and i have just written a method that returns all recipes with the same country. a country has many recipes as a relation
So my method is
def self.top_countries
joins(:recipes).
select('countries.*, count(*) AS recipes_count').
group('countries.id').
order('recipes_count DESC')
end
My controller
#worldrecipes = Country.where(:name => params[:name])
and view
<% #worldrecipes.each do |r| %>
<%= r.name %>
<% end %>
so accessing the country name attribute is easy as its in the country model and thats where my query results are being returned from (I think)...My question is how do i access the dish_name attribute from my recipe model to that links to the country name
Hope that makes sense, does anyone have a guide on how to work this out or some golden rules for this
Thank you

I think what you need is:
#country=Country.where(:name=>params[:name]).first
#worldrecipes=#country.recipes
And in the view:
<% #worldrecipes.each do |r| %>
<%= r.dish_name %>
<% end %>
This would print the dish names of the recipes of the country with name provided by params[:name]
EDIT:
Ok Let me clear this up for you :)
Your model relationship is setup such that each country has many recipes. i.e a country has many recipes.
So you have,
has_many :recipes
in country.rb and
belongs_to :country
in recipe.rb
Now when you want to access all the recipes belonging to a country, what you do is, you call country_record.recipes (country_record being the object of the country record you need).
And when you call,
Country.where(:name=>params[:name])
What you actually get is the active record object representing the COUNTRY itself and not the recipes of the country and that is why Italy was printed.
Hope this helped you.

For starters you want to make sure you have the association setup in your models:
country.rb
class Country < ActiveRecord::Base
has_many :recipes
end
recipe.rb
class Recipe < ActiveRecord::Base
belongs_to :country
end
If you haven't already done so, add a foreign_key attribute to your recipe model by running the following migration:
rails g migration add_country_id_to_recipe country_id:integer
Now that your associations are in place you can easily query for a countries respective recipes. In your controller:
#worldrecipes = Country.where(:name => params[:name])
Then in your view:
<% #worldrecipes.each do |c| %>
<% c.recipes.each do |r| %>
<%= r.dish_name %>
<% end %>
<% end %>
In regards to 'golden rules' I highly recommend you check out Association Basics. This is the go-to place for an overview of what you can do with associations.

Related

Rails List record and count for each

I have a model called Note. Each note belongs_to :call_reason. And call_reason has_many :notes.
What I want to do in a view is display a list of call_reasons and a total count of each next to it so we can see what the most popular call reasons are.
Here's what I have so far:
dashboard_controller:
def index
#notes = Note.all
end
dashboard view:
<% #notes.each do |n| %>
<%= n.call_reason.reason %>
<% end %>
This lists all notes' call_reasons.
I'm stumbling on how to list each call_reason once with a total count next to it. What I have now just lists all the call_reasons per note which is a mess. I think I could scope this out somehow or change the instance variable but I'm having a hard time getting it right.
Any thoughts?
Since you want to list call reasons, you should start with that:
def index
#call_reasons = CallReason.all
end
Then in your view you can do this:
<% #call_reasons.each do |call_reason| %>
<%= call_reason.reason %> <%= call_reason.notes.count %>
<% end %>
Note that this will perform a query for every call reason in your database. To prevent this you can use a counter cache. Check out the section on counter cache on Rails Guides too.

Rails cache not updating properly

I am using the cache-digests gem and following the instructions as per the Railscast, it creates and reads from a cache as you would expect, but the cache does not seem to be updating properly in relation to an associated record.
When moving a listing from one category to another, the category.live_entries count stays the same for the category I move it from, but goes up for the one I move it to.
So it sounds like I need a touch: all type method so it touches the one I am moving it from as well as the one it is moving to?
_category.html.erb
<% cache category do %>
<li>
<%= link_to category.name, category %>
<% if category.live_entries > 0 %>
(<%= category.live_entries %>)
<% end %>
- <%= category.desc %>
</li>
<% end %>
category.rb
class Category < ActiveRecord::Base
has_many :listings
def live_entries
listings.where(verified: true).count
end
end
listing.rb
class Listing < ActiveRecord::Base
belongs_to :category, touch: true
Any ideas on how to tackle this?
Guess I could create a before_update callback to touch the old category - but is there a better way?
Ok just adding this as an answer - but if anyone has a better solution please feel free to share.
I just added an after_update to touch the old category:
def touch_old_category(listing)
cat = listing.category_id_was
Category.find(cat).touch if cat
end

Listing records owned by the same model?

I have a simple Rails 3 application that has a number of models. A simple overview of the models I'm having trouble with is:
client model
has_many :animals
animal model
belongs_to :client
What I would to be able to do is show a list of other animals that are owned by the same client.
Something like this:
<% #client.animals.each do |animal| %>
<%= animal.AnimalName %>
<% end %>
As this is within the Animal controller, my example code won't work. Any pointers would be appreciated.
Update
To clarify, if I have the following records:
Danny (Client)
Cat (animal owned by Danny)
Dog (animal owned by Danny)
Rabbit (animal owned by Danny)
and I then went to the show view of the Dog's record, I would like a list that would show all animals that Danny owned. E.g.
Cat
Dog
Rabbit
Ideally excluding the currently viewed animal (in this case dog).
I have tried the following but it doesn't seem to work:
<% #client.animals.each do |client| %>
<%= #client.animal.AnimalName %>
<% end %>
If I understand you correctly you have #animal and want to show all the animals owned by the owner of #animal. This can be done like this:
<% #animal.client.animals.each do |animal| %>
<%= animal.AnimalName %>
<% end %>
Update:
You can just add a .where onto #animal.client.animals:
#animal.client.animals.where('id != ?', #animal.id).each ...
It's not such a good idea to do this in a view. So I would add an instance method to my Animal model:
def other_animals_with_same_owner
client.animals.where('id != ?', id)
end
With this you can do:
#animal.other_animals_with_same_owner.each ...

has_and_belongs_to_many validations

What is the most straightforward way to check to make sure a creation of a new record includes the creation of a related record via has_and_belongs_to_many? For example, I have:
class Person < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :people
end
I want a validation to fire on the creation of a new Person to make sure they belong to at least one group.
Also, how would I build this out in the controller? Right now I have:
def create
#person = current_user.people.new(params[:person])
end
I'd like params to include a group hash as well, to act as a sort of nested resource.
I've looked through the Rails documentation and I haven't been able to find anything on this particular case. If someone could explain this to me or point me in the right direction, I'd be very happy. Thanks!
If you want to give the user the option of creating one or more groups during the creation of a person, and then validate that those groups were created, please specify. Otherwise the remainder of this answer will be dedicated to creating a Person and validating that it is associated with at least one existing group.
If you're asking how to verify the existence of an Person-Group association on the groups_people join table, this could be done with weird sql queries and is inadvisable. Just trust that the well tested ActiveRecord works properly.
You can, however, validate the existence of one or more groups on a Person record before it is saved.
As long as you've migrated a join table called groups_people:
# db/migrate/xxxxxxxxxxxxxx_create_groups_people
class CreateGroupsPeople < ActiveRecord::Migration
def change
create_table :groups_people, :id => false do |t|
t.string :group_id, :null => false
t.string :person_id, :null => false
end
end
end
# $ rake db:migrate
, and your controller is correct:
# app/controllers/people_controller.rb
class PeopleController < ApplicationController
def new
#groups = Group.all
#person = Person.new
end
def create
#person= Person.new(params[:person])
if #person.save
# render/redirect_to and/or flash stuff
else
# render and/or flash stuff
end
end
end
, and you've all existing group options as checkboxes:
# app/views/people/new.html.erb
<%= form_for #person do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
# same for other person attributes
<% #groups.each do |g| %>
<%= check_box_tag 'person[group_ids][]', g.id, false, :id => g.group_name_attr %>
<%= label_tag g.group_name_attr %>
<% end %>
<%= f.submit 'Create!' %>
<% end %>
, then you can validate the presence of groups on your Person record:
class Person < ActiveRecord::Base
validates_presence_of :groups
has_and_belongs_to_many :groups
end
There is validates_associated helper, but wouldn't be necessary in this case, where you show Group.all as checkboxed options.
No accepts_nested_attributes_for is necessary for this. It would be if you were creating a Group for a Person while creating a Person. Again, please specify if this is the case.
Just a note: validating an incoming form that includes Group.all as options and gives the option of creating a group along with the person is possible but complicated. It would involve bypassing existing validations on the Group model, if any, which there probably is.

Multiple models, one form in rails. Want to create parent while creating the nested model object in a form

I want to update multiple models with one form in rails. I have looked at Railscasts #196 and many nested model examples but can't get them to work. The difference is I want to create a record in the parent model in a form for the child model.
I have these 3 models:
User Model
has_many :products
has_many :stores
Product Model
belongs_to :user
belongs_to :store
accepts_nested_attributes_for :store
Store Model
has_many: products
I have a form where a user can enter a product in. I want it to have a field where they can enter the store as well. This entry will create a record in the store model as well as product model with the store_id stored in the store model.
Form
<%= form_for #product, :html => { :multipart => true } do |f| %>
<%= f.text_field :product_name %>
<% f.fields_for :store do |store|%>
<%= store.text_area :store_name %>
<%end%>
<% end %>
Controller
#product = Product.new
#product.store.build
This code results in the following error :
undefined method `build' for nil:NilClass
I just want to be able to create a new store entry as they enter the product. (if it is a duplicate entry I will not allow it, but I will handle that elsewhere). Any suggestions?
accepts_nested_attributes_for
Only works for the one to one and one to many relationships, where you have the primary model is the main parent..
You would use it in the the User model for products and/or stores. However it looks like you want to create a new store when they enter a product in if the store doesn't exist right?
Since it appears your store is just a field or two I would just add the store in the controller using the fields for it..