Rails cannot Create Record with Active Record Associations - ruby-on-rails

My code works when I run the action like this,
def interest
#interest = Interest.new
#interest.user_id = current_user.id
#interest.idea_id = #idea.id
#interest.save
#ideas = Idea.take(10)
flash[:notice] = "A message has been sent to the poster."
render "ideas/forum"
end
But,why do I get an undefined method for 'interest' when I use this line in my Interest action?
#interest = current_user.ideas.interest.create(params[:interest])
Here's my Idea model
class Idea < ActiveRecord::Base
belongs_to :user
:title
:category
:content
:user_id
:createdDate
:updatedDate
Here's my User model (Devise)
class User < ActiveRecord::Base
has_many :ideas
has_many :interests
end
Here is the button_to tag
<%= button_to "I'm Interested", ideas_interest_path(:id => idea.id, :idea_id => idea.id, :user_id => idea.user_id) ,class: 'btn btn-primary' %>
And my route,
resources :ideas do
resources :interests
end
Interest Model
class Interest < ActiveRecord::Base
belongs_to :user
belongs_to :idea
has_many :users
:idea_id
:user_id
end
NoMethodError - undefined method `interest' for #<Idea::ActiveRecord_Associations_CollectionProxy:0x007f9e5189bab0>:
activerecord (4.2.0)

I think you messed up the association, I'd do:
class User < ActiveRecord::Base
has_many :interests
has_many :ideas, through: :interests
end
class Interest < ActiveRecord::Base
belongs_to :user
belongs_to :idea
# user_id, idea_id
end
class Idea < ActiveRecord::Base
has_many :interests
has_many :users, through: :interests
end
Then I guess the rest would work.

Related

Validates uniqueness record per user per lesson // Rails 4

Problem: I want to have only 1 UserLesson per User per Video
because I'm building a tracking system (progress system) User shall be able to see how many lessons are remaining lesson/total lesson and also when marked as completed shall add css
I send the data from the view to the controller:
<%= link_to 'Mark as completed', user_lessons_path(#user_lesson, user_lesson: {user_id: current_user.id, lesson_id: #lesson.id}), :method => :post, class: 'btn btn-primary-big' %>
The controller receives data and launch the create method
class UserLessonsController < ApplicationController
before_filter :set_user_and_lesson
def show
end
def create
#user_lesson = UserLesson.create(user_lesson_params)
if #user_lesson.save
flash[:success] = "You rock! Keep up ;)"
redirect_to(:back)
else
flash[:success] = "You have already completed this lesson"
redirect_to(:back)
end
end
private
def user_lesson_params
params.require(:user_lesson).permit(:user_id, :lesson_id, :completed)
end
end
Here is the model relationship
class UserLesson < ActiveRecord::Base
belongs_to :user
belongs_to :lesson
# validates_uniqueness_of :user_lesson, :scope => [:user, :lesson]
end
class Lesson < ActiveRecord::Base
has_one :lecture, through: :chapter
belongs_to :chapter
end
class User < ActiveRecord::Base
has_many :enrollments
has_many :user_lessons
has_many :lectures, through: :enrollments
accepts_nested_attributes_for :enrollments
end
class Enrollment < ActiveRecord::Base
belongs_to :user
belongs_to :lecture
validates :lecture, uniqueness: { scope: :user, message: "should happen once per user" }
end
class Lecture < ActiveRecord::Base
belongs_to :category
has_many :lessons, through: :chapters, dependent: :destroy
has_many :chapters
belongs_to :teacher
# For course user relationship
has_many :enrollments
has_many :users, through: :enrollments
accepts_nested_attributes_for :enrollments
accepts_nested_attributes_for :chapters
end
class Chapter < ActiveRecord::Base
has_many :lessons
belongs_to :lecture
accepts_nested_attributes_for :lessons
end
My guess was to validates uniqueness of user-lesson per user and lesson. However can't seem to work got the error message.
Add this validation to your model to ensure uniqueness by user scope:
validates :lesson_id, :uniqueness => {:scope=>:user_id}

Displaying nested association in view in Rails 4

I have 3 models as below:
class Kick < ActiveRecord::Base
has_many :offs
has_many :retailers, :through => :off
end
class Retailer < ActiveRecord::Base
has_many :offs
has_many :kicks, :through => :off
end
class Off < ActiveRecord::Base
belongs_to :kicks
belongs_to :retailers
end
And I'm trying to display the name of the retailer in my 'show Kick view' as below:
<% #kick.off.each do|off| %>
<%= off.name %>
<%= off.retailers.name %>
<% end %>
Off.name displays fine but I cannot seem to index the retailer's name from this view. What am I missing?
Error:
undefined method `name' for nil:NilClass
class Kick < ActiveRecord::Base
has_many :offs
has_many :retailers, :through => :offs
end
class Retailer < ActiveRecord::Base
has_many :offs
has_many :kicks, :through => :offs
end
class Off < ActiveRecord::Base
belongs_to :kick
belongs_to :retailer
end
also make sure you properly indexed the models in db
class Kick < ActiveRecord::Base
has_many :offs
has_many :retailers, :through => :offs
end
class Retailer < ActiveRecord::Base
has_many :offs
has_many :kicks, :through => :offs
end
class Off < ActiveRecord::Base
belongs_to :kick
belongs_to :retailer
end
#kick = Kick.includes(:retailers => :offs).where('kicks.id' => 1).select('retailers.name, kicks.*')
In the view it should be kick.offs not kick.off
<% #kick.offs.each do|off| %>
<%= off.name %>
<%= off.retailers.name %>
<% end %>

Many to many realationship and join in rails 3

I have following three models
class Rating < ActiveRecord::Base
belongs_to :user
belongs_to :book
end
class User < ActiveRecord::Base
attr_accessible :name, :dob, :mobile
has_many :books, :through => 'ratings'
end
class Book < ActiveRecord::Base
attr_accessible :book_name, :author, :pages
has_many :users, :through => 'ratings'
end
Now I have to find all the "book_name"s of each book which is related the respective user and store it in the array.
Here is code
#book_names = []
#books = Rating.find(:all, 'user_id = ?', current_user.id)
#books.each do |book|
book_info = Book.find(book.id)
#book_names << book_info.book_name
end
Is there any other way for the same or join method.
Yes, there is simple way to do it. Try
#book_names= current_user.books.map(&:book_name)

Why wont Rails save the joiner model? Normal behavior or a bug?

The joiner model is not being saved when I try this (assumingAccount has_many :users, through: :roles and vice-versa):
def new
#account = current_user.accounts.build
end
def create
#account = current_user.accounts.build(params[:account])
#account.save # does not save the joiner model
end
That should create #account, and a Role record where user_id=current_user.id and account_id: #account.id. Only #account gets saved. There are not records in the Role model. The results are consistent using console.
Replace current_user.accounts.build with current_user.accounts.create in the create action, the joiner (role record) model gets saved. For this reason I don't think this is a validation issue. I'm using Rails 3.2.3.
Models:
class User < ActiveRecord::Base
has_many :roles
has_many :accounts, through: :roles
end
class Account < ActiveRecord::Base
has_many :roles
has_many :users, through: :roles
accepts_nested_attributes_for :users
end
class Role < ActiveRecord::Base
attr_accessible
belongs_to :users
belongs_to :accounts
end
View
<%= simple_form_for(#account) do |f| %>
<%= render 'account_fields', f: f %>
<%= f.submit %>
<% end %>
Try to use
UPDATED:
class User < ActiveRecord::Base
has_many :roles
has_many :accounts, through: :roles, :autosave => true
end
You can find more info about autosave here.
or using a callback in User model
after_save :save_accounts, :if => lambda { |u| u.accounts }
def save_accounts
self.accounts.save
end
This is a bug: https://github.com/rails/rails/issues/6161#issuecomment-5631018

NoMethodError? Counting Records

I have the following models:
class Label < ActiveRecord::Base
has_many :releases
end
class Release < ActiveRecord::Base
belongs_to :label
has_many :products
has_and_belongs_to_many :tracks
def self.releases_count
self.count(:all)
end
end
class Product < ActiveRecord::Base
belongs_to :release
has_many :releases_tracks, :through => :release, :source => :tracks
has_and_belongs_to_many :tracks
def self.products_count
self.count(:all)
end
end
On my label/index view i'm able to display a count of the Releases absolutely fine using:
<%= label.releases.releases_count %>
I'm trying to do the same for Products using:
<%= label.releases.products.products_count %>
But get a NoMethodError:
undefined method `products' for #<Label:0x10ff59690>
Any ideas?
I have lots of other aggregations I want to perform (Track Counts etc) so some guidance on where I'm going wrong would be really appreciated.
You need define your production/Label association
class Label < ActiveRecord::Base
has_many :releases
has_many :products, :through => :releases
end

Resources