Connecting two models in rails - ruby-on-rails

I am trying to call value from another model inside the views.
tse.headoffice.head_office_id
Defined the relationship in headoffice.rb as
has_many :tse
and in tse.rb as
belongs_to :headoffice
Now I am getting an error as undefined method
undefined method `head_office_id' for nil:NilClass

<% if tse.headoffice.present? %>
<%= tse.headoffice.head_office_id %>
<% end %>

try() lets you call methods on an object without having to worry about the possibility of that object being nil and thus raising an exception
<%= tse.try(:headoffice).try(:head_office_id) %>

Assuming that the HeadOffice model has an attribute called head_office_id:
<%= tse.headoffice.head_office_id if tse.headoffice %>
If that's not the case:
<%= tse.headoffice_id %>

Something about this doesn't look right. Usually the has_many reference is plural. It's possible your naming scheme is messing with Rails' opinionated magic.
Also why would headoffice have a field called headoffice_id? Wouldn't it just have a field called id? Finally, one nitpick, it should be called head_office not headoffice. And tse is not a good name either. What is tse? Spell it out if you can and form it in a manner that can be singular or plural. Rails works much better if you follow these simple naming guidelines.
https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e
See the simple example below:
post.rb
has_many :comments
comment.rb
belongs_to :post
To access a post's comments you'd type the following:
Post.first.comment.body
Or if you're uncertain about a post having a comment you'd say:
Post.first.try(:comment).try(:body)

Related

Use rails_admin forms in custom views?

I am making my own custom view that I need to make the process of creating associated models less painful for my users. I want to display all of the models associated pieces in-line, with controls to edit them. This is quite easy to roll my own for the basic fields, but I'd rather use a form_filtering_select partial for the inline model's associations, but I can't find any documentation to do this.
You can use Nested Form
Consider a User class which returns an array of Project instances from the projects reader method and responds to the projects_attributes= writer method:
class User
def projects
[#project1, #project2]
end
def projects_attributes=(attributes)
# Process the attributes hash
end
end
Note that the projects_attributes= writer method is in fact required for fields_for to correctly identify :projects as a collection, and the correct indices to be set in the form markup.
When projects is already an association on User you can use accepts_nested_attributes_for to define the writer method for you:
class User < ActiveRecord::Base
has_many :projects
accepts_nested_attributes_for :projects
end
This model can now be used with a nested fields_for. The block given to the nested fields_for call will be repeated for each instance in the collection:
<%= nested_form_for #user do |user_form| %>
...
<%= user_form.fields_for :projects do |project_fields| %>
<% if project_fields.object.active? %>
Name: <%= project_fields.text_field :name %>
<% end %>
<% end %>
...
<% end %>
Here goes the Reference for details.
There's a cool gem out there that does pretty much what you want. It's called Nested Form Fields. It allows you to edit records (along with their has_many associations) on a single page. The cool thing about it is that it even uses jQuery to dynamically add/remove form fields without a page reload. Checkout out the gems docs for proper usage. Hope that helps!

Is Property in any way reserved for rails model naming? (Rails pluralisation is killing me.)

I am trying to add a model called Properties in Rails 3.1 So I used created it using ryan bates nifty generator, although the model itself is very basic for now and only includes.
class Property < ActiveRecord::Base
belongs_to :user
end
in my resources I have"
resources :properties
In one of my views I am simply trying to do the following:
<% for property in Property.all %>
<p>description etc</p>
<% end %>
but it gives me the following error?!
undefined method `all' for Property:Module
Now it works if I replace Property.all with User.all or House.all but for some reason Property doesn't work. I'm kinda new to rails and think it has something to do with pluralization but I can't figure it out and its killing me. If anyone could please help that would be epic! Cheers
You can use Inflections to extend default dictionary ( peoperty word is not included by default). The official API can help you with it
In your model definition you need to tell it the real name of your table, eg.
class Property < ActiveRecord::Base
set_table_name "properties"
end
Also you may want to adapt the code slightly for showing your data, it's better to use your controller to grab the data, and the view to display it
In your controller
def index
#properties = Property.all
end
In your view
<% #properties.each do |property| %>
<%= property.description %>
<% end %>

Rails 3 get Username by ID

How can I get the Username from an ID in Rails 3?
In my view I call <%= blog.user_id %> for the ID, but how do I get the Name there?
The Controller is a scaffold default.
Make sure you define the association in your Blog model.
belongs_to :user
And then in your view your can use <%= blog.user.name %>
Generally you want to avoid long chains of dots like post.user.name. Try:
class Post < ActiveRecord::Base
belongs_to :user
delegate :name, :to => :user, :prefix => true
end
Then in your views you can call
#post.user_name
to get the users name. I thought I would throw this out there since its good habit I am trying to include in my code as well.
You should use <%= blog.user.name %> and have defined
belongs_to :user
in your Blog model. You should work with ..._id on the view-level.
you should learn how to code in Rails, this is a very basic question.
Consider having a look at http://railsforzombies.org
It's a great online tutorial
Try using <%= blog.user.try(:name) %>

Rails 3 has_and_belongs_to_many creates checkboxes in view

Based on following models
class Company < ActiveRecord::Base
has_and_belongs_to_many :origins
end
class Origin < ActiveRecord::Base
has_and_belongs_to_many :companies
end
I want to have in my companies/_form a collection of checkboxes representing all origins.
Don't know if the Company.new(params[:company]) in companies_controller#create can create the association between company and the selected origins?
I'm running rails 3.0.0, what is the best way to achieve that?
thanks for your insights
habtm isn't a popular choice these days, it's better to use has_many :through instead, with a proper join model in between. This will give you the method Company#origin_ids= which you can pass an array of origin ids to from your form, to set all the associated origins for #company. eg
<% current_origin_ids = #company.origin_ids %>
<% form_for #company do |f| %>
<label>Name:<%= f.text_field :name %></label>
<% Origin.all.each do |origin| %>
<label><%= origin.name %>
<%= check_box_tag "company[origin_ids][]", origin.id, current_origin_ids.include?(origin.id) %>
</label>
<% end %>
<% end %>
As an aside, using a proper join model, with corresponding controller, allows you to easily add/remove origins with AJAX, using create/delete calls to the join model's controller.
I have to agreed with #carpeliam a has_many :through should not be the default choice. A HABTM works fine and involves less code. It also does not restrict the use of ajax and does expose a origin_ids setter to which you can pass an array of ids. Therefore the screencast, whilst from 2007, still works with Rails 3. The other option if using simple_form is this:
= form.association :origins, :as => :check_boxes
Personally I'm not of the belief that has-many-through is always better, it really depends on your situation. Has-many-through is better if there is ANY possibility of your join model having attributes itself. It's more flexible to change. It removes the magic of some Rails conventions. If however you don't need has-many-through, then there's an old RailsCast for HABTM checkboxes that might come in handy.

Rails Polymorphic relationship and link_to

Here's my Schema
class Menu < ActiveRecord::Base
belongs_to :menuable, :polymorphic => true
end
class Page < ActiveRecord::Base
has_one :menu, :as => :menuable
end
class Links < ActiveRecord::Base
has_one :menu, :as => :menuable
end
I want to link to a polymorphic class in the Menu view using link_to, e.g.
<%= link_to menu.name, menu.menuable %>
This works, but this retrieves the menuable object from the database, when all I wanted is to generate a link. You can imagine if my menu is large, this will really bog down my application.
When I decared the menuable field as polymorphic, Rails created menuable_type and menuable_id. What can I use to generate a link to the polymorphic page, short of writing a helper function with a giant switch statement (e.g. if I have a large number of menuable 'subclasses'?)
It's been long since the question was asked but I had the same problem recently and the solution was to use polymorphic_url. You need to find the name of the route you need to create a link to, for example "fast_car_path" and make it out of your *_type and *_id from polymorphic table. For example, you have a list of comments and want to make the link to the cars that they belong to. So if *_type = FastCar we have
#comments.each do |comment|
link_to polymorphic_url(comment.commentable_type.tableize.singularize, :id => comment.commentable_id)
which will generate "fast_car_path" without downloading the cars from database.
I am a noob in rails and I dont know how good that advice is, but I hope it will be helpful for somebody.
You could do something like this:
def my_menu_url(menu)
"/#{menu.menuable_type.tableize}/#{menu.menuable_id}"
end
if you use the rails convention for naming the controllers that correspondent to your models.
But don't do it. You work around the routing mechanism of rails and that's simply bad practice.
You should use the :include option in your finders to eager load your menuables:
Menu.all :include => :menuable
In the case this isn't enough you may use some sort of caching.
Another approach could be to use url_for[menu.menuable, menu]. So, the link tag would look like so: <%= link_to menu.name, url_for([menu.menuable, menu]) %>.
you could use polymorphic routes for this
https://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html
<%= link_to menu.name, polymorphic_path(menu.menuable) %>
it will generate html like this
menu.name

Resources