belongs_to on activerecord rendering as not found - ruby-on-rails-3

I must be doing something stupid here. I am using rails 3.2.19 with activeadmin 0.6.0. Basically I'm trying to do a navigate down through a belongs_to association via a side bar. I have loaded my database with text fixtures and can drill down through the association at the rails console, i.e:
2.1.1 :004 > Employee.first.blogposts.first
Employee Load (0.1ms) SELECT "employees".* FROM "employees" LIMIT 1
Blogpost Load (0.1ms) SELECT "blogposts".* FROM "blogposts" WHERE "blogposts"."employee_id" = 615722309 LIMIT 1
=> #<Blogpost id: 298486374, title: "Mine too", body: "Can we try markdown?", employee_id: 615722309, created_at: "2014-07-25 03:27:14", updated_at: "2014-07-25 03:27:14">
2.1.1 :005 >
My model associations are nothing fancy. Basically as simple as they can be:
class Blogpost < ActiveRecord::Base
belongs_to :employee
end
class Employee < ActiveRecord::Base
has_many :blogposts
end
And the same with my active admin resources. I built these based on the documentation.
ActiveAdmin.register Employee do
sidebar "Details", only: [:show, :edit] do
ul do
li link_to("Blogposts", admin_employee_blogposts_path(employee))
end
end
end
ActiveAdmin.register Blogpost do
belongs_to :employee
end
I can also see the route specified when I do rake routes
admin_employee_blogposts GET /admin/employees/:employee_id/blogposts(.:format) admin/blogposts#index
The link on the employee page (the one defined at the Employee resource) renders without error, however when I click on it I receive:
NoMethodError in Admin::BlogpostsController#index
undefined method `find' for nil:NilClass
Parameters:
{"employee_id"=>"615722309"}
The URL specified in the browser is:
http://localhost:3000/admin/employees/615722309/blogposts
Does anybody know how to troubleshoot this? I am certain that the particular employee ID in question has blog posts, as I demonstrated by using the rails console. Any help anybody could provide would be greatly appreciated.
Thank you,
Dan Sullivan

Try using this:
ActiveAdmin.register Blogpost do
belongs_to :employee, parent_class: Employee
end

Related

Rails - Show action for nested resource is deleting the record?

I am building a simple web app with a typical User model & Profile model. The user model has_one profile & the profile model belongs_to user. All is going pretty well as I am basically following Michael Hartl's tutorial (except he uses has_many for microposts).
So here's the deal. I create a user, then create a profile. I know both records exist b/c I verify their presence in my sqlite3 db browser. However, as soon as I try to render the show view by visiting -> localhost/3000/profiles/1, I get the error shown below. But the even weirder part is that now when I check my db, the profile record is gone. Please help!
Note: I have a feeling it has something to do with dependent destroy (b/c removing it will eliminate this issue), but I have no idea why. Furthermore, I think I want dependent destroy anyway. I don't want any stray profile records if there are no corresponding users, right?
Routes
resources :users
resources :profiles
Models
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
class Profile < ActiveRecord::Base
belongs_to :user
ProfilesController
def new
#profile = current_user.build_profile
end
def create
#profile = current_user.build_profile(params[:profile])
if #profile.save
flash[:success] = "Profile created!"
redirect_to root_path
else
render 'new'
end
end
def show
#profile = Profile.find(params[:id])
end
views/profiles/show.html.erb
<p>Display Name: <%= #profile.display_name %></p>
This is the error message I get when I try to visit -> localhost/3000/profiles/1
ActiveRecord::RecordNotFound in ProfilesController#show
Couldn't find Profile without an ID

Setup rails3 text_field for rocket_tag tag list

This is the first time I've tried to add a tags field to a form so bear with me.
I'm using:
rails 3.2.8
Postgres 9.1
rocket_tag 0.5.6
squeel 1.0.9
I have installed the rocket_tag gem and run the various commands
rails generate rocket_tag:migration
rake db:migrate
rake db:test:prepare
to set everything up.
I've amended my Meeting model:
*Adding :tags and :tag_list to attr_accessible
*Adding attr_taggable :tags
*I've added a virtual attribute for displaying the tag list in the form field:
def tag_list
self.tags.join(",")
end
def tag_list=(new_tags)
self.tags = new_tags.split(/,[\s]*/).reject(&:empty?)
end
*I have added f.text_field :tag_list to my form view
This left me with my list page not working though. It said Association named 'taggings' was not found; perhaps you misspelled it?
User
has_many :meetings
has_many :meeting_dates, :through => :meetings
Meeting
belongs_to :user
has_many :meeting_dates
Meeting Dates
belongs_to :meeting
In my list page I list meeting dates using:
user_meeting_dates = #user.meeting_dates.includes(:meeting => :user)
To get past the taggings error I seem to need to have the following in my Meeting Dates model:
has_many :taggings, :through => :meeting
has_many :tags, :through => :taggings
Can someone explain why I need these here and whether there's a way to tidy this up any more, it doesn't seem like it's right.
Should it not be possible to do something like:
user_meeting_dates = #user.meetings.meeting_dates
Thanks
Once I've got this working correctly I can move on to apply Select2 to my tags field but I need to get it working just from a plain text field first.

rails 3 model relation with has_and_belongs_to_many

I got these three models:
Projects, Organisms and Sequences
Each sequence is unique and belongs to an organism. An organism can have many sequences. So far, it works fine.
The problem I am struggling with is the association in my projects model:
I need to select one organism and one of the to the organism associated sequences to the project. But also, an organism can have many projects.
I was following these instructions : has_and_belongs_to_many-associations-in-ruby-on-rails. But it fails, when I try save my form data. When I try to "build" it in the console, it even fails:
ree-1.8.7-2011.03 :001 > project = Project.new
=> #<Project id: nil, name: nil, organism_id: nil, sequence_id: nil, created_at: nil, updated_at: nil>
ree-1.8.7-2011.03 :002 > project.organism.build
NoMethodError: undefined method `organism' for #<Project:0x56117c8>
What's wrong with what I'm doing?
Maybe i am following the wrong path here. im not very good in database design, so i need some help obviously :) What i'd like to have is something like project.organism and project.sequence as well as sequence.organism and origanism.sequences. You see, the three models are close connected to each other. The background is, that a rake task will update the list of the organisms and the associated sequences regulari form NCBI database. Therefore i cant just "save" the data in the projects model, i have to link them to other tables.
EDIT: my Project Model looks like this:
class Project < ActiveRecord::Base
has_and_belongs_to_many :organisms
#has_one :sequence
end
note: i still have no idea, how to make the sequence available to the project.
and the migration:
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.string :name
t.integer :organism_id
t.integer :sequence_id
t.timestamps
end
end
end
thank you four your help,
Adrian
EDIT 2:
i think i have solved it. I just rethought about that, and this is the more simple solution:
class Project < ActiveRecord::Base
belongs_to :organism
belongs_to :sequence
end
class Sequence < ActiveRecord::Base
belongs_to :organism
end
class Organism < ActiveRecord::Base
has_many :projects
has_many :sequences
end
The problem with this is only that i cant go back from sequences to projects like sequence.projects
try
project.organisms.build
instead of
project.organism.build
You did called the association organisms after all :)

Related Object Query Rails 3

I'm developing a blog site for practice. My problem is I can't call data from one object to another related object.
Here are my model associations:
1 class Post < ActiveRecord::Base
2 belongs_to :user
3 end
1 class User < ActiveRecord::Base
2 has_many :posts
3 end
In the console:
user = User.find(1)
user.posts // Everything works! It shows me a list of posts related to the user.
user.post(1) //This doesn't work! Is it wrong?
I've been looking over active record query interface guide at rubyonrails.org and still can't find anything in reference to this. Maybe I missed something?
Thanks
Do it this way:
user.posts[0] #=> returns the user's first post

Rails 3 - associations

I print in my view a number that tell me, how many people read my article. It looks something like a:
<%=article.hits.count%>
As is possible to see, I created a simple association.
Now I am trying to get the information, if the user who is log in on my page, so if he is already had read this article. In my table that contains hits is column user_id.
But I can't still find the way, how to get...
I tried something like:
<% if session[:login_user_id].hits.user_id == session[:login_user_id]%>
Have you read it already.
<% end %>
But the example above doesn't work me... Could anyone help me please, how to do?
EDIT: The models:
class Article < ActiveRecord::Base
has_many :hits
end
class Hits < ActiveRecord::Base
belongs_to :article, :class_name => "DataHit", :foreign_key => "article_id"
has_many :users
end
class User < ActiveRecord::Base
belongs_to :hit
end
Thanks in advance
Let's first talk about the model you like to receive. For me, it sounds like:
Every article can be visited / read by many users.
Every user can read / visit many articles.
This is a classical n:m-association which is normally implemented by a has-many-through association.
If this is the intention, it should be implemented like:
class Article < ActiveRecord::Base
has_many :hits
has_many :users, :through => :hits
end
class Hits < ActiveRecord::Base
belongs_to :article, :class_name => "DataHit", :foreign_key => "article_id"
belongs_to :user
end
class User < ActiveRecord::Base
has_many :hits
has_many :articles, :through => :hits
end
Of course, you have to add migrations that ensure that the final DB model is like that:
Hit has article_id and user_id to ensure that users may find the articles they have read
If you have that model implemented, it should be more easy. Then you have operations available like: #article.users.contains(User.find(user_id)). Have a look at the tutorial at Ruby on Rails Guides which explain what the has-many-through relation is and which advantages they have.
It would be helpful if you try the things first in the console of Rails. To do that, start with:
Start the rails console in the root directory of your application: rails c
Enter there e.g.: art = Article.find(1) to get the article with the id.
Try which methods are available: art.methods.sort to see all methods that could be used. If there is no method users, you have did something wrong with the assocication.
Try the call: us = art.users and look at the result. It should be a rails specific object, an object that behaves like a collection and understands how to add and remove users to that collection (with the whole life cycle of rails). The error your currently have could mean different things:
Your database model does not match your associations defined in Rails (I suspect that).
Some minor tweak (misspelling somewhere) which hinders Rails.
I hope this gives you some clues what to do next, I don't think that we can fix the problem here once and for all times.