Nil class error for association - ruby-on-rails

I have a model Tutorial and has_many association Tutorialcategory where tutorials can be connected to many tutorial categories. Tutorials model and controller are working fine but categories are not. I am able to add categories but can not edit them, I am getting 'undefined method `model_name' for NilClass:Class' error while accessing edit page for tutorialcategory.
I have defined route as follows
resources :tutorialcategories do
end
following is my model definition
class Tutorial < ActiveRecord::Base
has_many :tutorialcategories

If you can add categories but not edit them then you must load a #tutorial_category variable in your edit action, something like this:
def edit
#tutorial_category = TutorialCategory.find params[:id]
end

Related

How to destroy a record when there is many-to-many relationship in ruby on rails?

In my app there is recipes and ingredients, so a recipe can have many ingredients and a ingredient can be used in many recipes, everything is ok and when I create recipes there is a table called Has_ingredient where is saved every ingredient per recipe.
The thing is, now when I try to destroy a recipe there is a error, because I need to destroy the record in Has_ingredient associated with that recipe before delete the recipe.
So in my model I created something like this
class Recipe < ActiveRecord::Base
before_destroy :destroy_ingredents
....
....
....
def destroy_ingredents
HasIngredent.destroy(recipe_id: self.id)
end
Well, now I get this error: OCIERROR: ORA-00904.
So now the problem is not Rails, but the database (Im using Oracle), but im pretty sure the problem is how im using destroy method but I cant figure how to use it properly to delete every record in has_ingredent table associated with certain recipe
The best way to destroy the children would be using the dependent
So in your model, you would have:
class Recipe < ActiveRecord::Base
has_many :ingredients, dependent: :destroy
end
As #pauloancheta suggested, is the better way to leave these with rails. However if you want to know the correct syntax,
HasIngredent.find_by(recipe_id: self.id).destroy

How to create controllers in different namespace for an existing model?

I have a Product model in my rails app. Now I want to create a controller and views for this product model through scaffolding in a different namespace(api).
Till now I have tried using
rails g scaffold_controller product name:string price:integer
and after this I added the this to my routes file
namespace :api do
resources :products
end
Now when I go to the link api/products . I get this error
uninitialized constant Api::Product
on the index action
def index
#api_products = Api::Product.all
end
After this I removed the Api:: from my controller index, new and create action. After doing this my index url (/api/products) was working fine but now when I try to create a new product(/api/products/new) I get the following error
undefined method `products_path'
This is the code for my model file (location is models/)
class Product < ActiveRecord::Base
end
Can anyone please help in implementing this correctly?
You should move product.rb to app/models/api and change the class name to Api::Product
#app/models/api/product.rb
class Api::Product < ActiveRecord::Base
self.table_name = "products"
end

undefined method 'article' - use data from other model

There are articles and comments.
article has_many :comments
comment belongs_to :article
I want to get all comments where value_id is equal to value_id attribute in the article that comment belongs_to.
class Comment < ActiveRecord::Base
belongs_to :article
def self.value_comments
where(value_id: self.article.value_id)
end
end
I get an error:
undefined method `article' for #<Class:0x007fd2a7e46d18>
controller
#value_comments = Comment.value_comments.where(user_id: current_user.id).order("created_at desc")
Having read your question again, my understanding is that you want to find all Comments whose value_id matches the value_id of their associated Article.
Your code is nearly correct - you need a few more parts to get this to work. You need to join your Comment table to your Article table using joins. Then, refer to the column in a where function using arel_table.
So you should end up with something like this:
def self.value_comments
joins(:article).where(self.arel_table[:value_id].eq Article.arel_table[:value_id])
end
You could also consider using sexy_scopes to make it easier to access your columns.

rails view has_many relation

I have such two models:
class Article < ActiveRecord::Base
belongs_to :articles_type
end
class ArticlesType < ActiveRecord::Base
has_many :articles
end
and in controller i write:
#articles = Article.where(article_type_id: params[:id])
and in view(haml) i try:
= #articles.articles_type.id
= #articles.articles_types.id
= #articles.first.articles_type.id
= #articles.first.articles_types.id
how could i display this articles_type.id but for only first row?
now i get
undefined method `articles_type'
but why? what i do wrong? how to display nested model id?
#articles will be a collection of items, not just a single one (because you used the where method). You will have to do:
#articles.first.articles_type_id
(Also note that you don't have to do .articles_type.id, because the #articles.first already has the ID of the type)
The undefined method message is because #articles does not have an articles_type method. You have to get to a single instance of an Article in order to use that method. You could do that with a call to #articles.first or by iterating on the collection.
= #articles.first.articles_type.id
is the line you want to use.
Looks like you've got your logic backwards.
Based on your models, an article belongs to an article_type.
#articles.first.article_type.id
# OR #articles.first.article_type_id
Just looks like you're incorrectly pluralizing .article_types when it should be .article_type.

How can I fetch all the associated records?

Current_user has many favorite communities. Favorite communities can be fetched by this.
#communities = current_user.get_up_voted(Community)
Then each community has many topics just like this.
Community has_many: Community_topics
Community_topic belongs_to: Community
Now, how can I fetch all the topics that are belonging to current_user's favorite communities?
I tried this
#communities = current_user.get_up_voted(Community)
#community_topics = Community_topics.where(:community_id => #communities).page(params[:page]).order("last_active_at DESC")
But I got this error:(
NameError (uninitialized constant UsersController::Community_topics):
Follow the documentation to the letter:
A has_many association indicates a one-to-many connection with another
model. You’ll often find this association on the “other side” of a
belongs_to association. This association indicates that each instance
of the model has zero or more instances of another model.
Make sure your spelling is correct, that you have a parent_table_id field in the child table, and you have declared that the child table belongs_to its parent.
If you make a model:
e.g. my_model.rb
it contents should looke like this:
class MyModel < ActiveRecord::Base
end
so in controller you will call it:
#myvariable = MyModel.where(......)
Make sure of your naming conventions. Check if they are correct.

Resources