Select data from two tables and listing - mysql

I have following structure:
class User < ActiveRecord::Base
has_many :Hobbies, :dependent => :destroy
accepts_nested_attributes_for :hobbies, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
class Hobby < ActiveRecord::Base
belongs_to :User
end
In my Users_controller.rb
def index
#data = User.all(:joins => :hobbies)
end
In index.html.erb
<% for item in #data %>
<tr>
<td><%= item.id %></td> #from table Users
<td><%= item.hobby_name %></td> #from table Hobbies
</tr>
<% end %>
And this gives me an error undefined method `hobby_name' for # User:0x103cf7480>
I thought that I have that associations right, but this error makes confused... Can you help me someone, please, where could be a problem?

You must specify the relation, your object doesn't have an attribute called hobby_name, it has an association to multiple hobbies, and each hobby has an attribute called hobby_name
So:
<% item.hobbies.each do |h| %>
<%= h.hobby_name %>
<% end %>

Related

nested user-specific forms in rails

I'm attempting to build a nested form for my Devise users to fill out and then later update. The form consists of two models; one for questions and another for users. My controller looks like this:
class LegalFormsController < ApplicationController
before_action :set_legal_form, only: [:show, :edit, :update, :destroy, :answers]
respond_to :html
def index
#legal_forms = LegalForm.all
respond_with(#legal_forms)
end
def show
respond_with(#legal_form)
end
def new
#legal_form = LegalForm.new
respond_with(#legal_form)
end
def edit
end
def create
#legal_form = LegalForm.new(legal_form_params)
#legal_form.save
respond_with(#legal_form)
end
def update
#legal_form.update(legal_form_params)
respond_with(#legal_form)
end
def destroy
#legal_form.destroy
respond_with(#legal_form)
end
def answers
#users = User.all
#questions = #legal_form.questions
end
private
def set_legal_form
#legal_form = LegalForm.find(params[:id])
end
def legal_form_params
params.require(:legal_form).permit(:name,
:questions_attributes => [:id, :content,
:answers_attributes =>[:id, :content, :participant_id]
])
end
end
and the view for the answers is (currently) as follows:
<h1><%= #legal_form.name %> Answers</h1>
<%= form_for(#legal_form) do |f| %>
<% #users.each do |user| -%>
<h3><%= user.id %></h3>
<table>
<thead>
<tr>
<td>Questions</td>
<td>Answer</td>
</tr>
<tbody>
<% #questions.each do |question| -%>
<tr>
<td><%= question.content %></td>
<td>
<%= f.fields_for :questions, question do |q| -%>
<%=q.fields_for :answers, question.answers.find_or_initialize_by(user: #user) do |a| -%>
<%= a.text_area :content %>
<%= a.hidden_field :user_id, :value => current_user %>
<% end -%>
<% end -%>
</td>
</tr>
<% end -%>
</tbody>
</table>
<% end -%>
<div class="actions">
<%= f.submit %>
</div>
<% end =%>
As you can see, this currently brings up all questions/answers for all users.
My question is two-fold:
How might I set this up to just bring up the current user?
Using this line <%= a.hidden_field :user_id, :value => current_user %>, I am attempting to provide the current user id for each answer saved to the answers database under user_id. However, it doesn't seem to be working. What might I be missing?
Many thanks for any help on this!
As requested, below are my model associations
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :user
end
class LegalForm < ActiveRecord::Base
has_many :questions
accepts_nested_attributes_for :questions
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :answers
has_many :questions, through: :answers
end
class Question < ActiveRecord::Base
belongs_to :legal_form
has_many :answers
has_many :users, through: :answers
accepts_nested_attributes_for :answers
end
You can set user_id value like this
<%= f.hidden_field :user_id, value: current_user.id %>

Assign foreign key in ruby rails

I am new to rails and I am having a hard time assigning the foreign key user_id to user_profile.
When a user creates an account it is saved to the database, then they are taken to create a profile. The user can create the profile and the profile is saved to the database. I used to have
<tr>
<th><%= f.label(:user_id, "User ID") %></th>
<td><%= f.text_field(:user_id) %></td>
</tr>
assign
on the user profile form, and it worked, user.user_profile showed there was a relationship. but I don't want a user to have to/be able to choose the user_id they are creating a profile for. I can't figure out how to assign the user_id to the user_profile. in the controller for user_profiles I have
def new
#user = User.find(session[:user_id])
#user_profile = UserProfile.new({:user_id => #user.id})
end
and for the new page for user_profiles I have
<%= form_for(:user_profiles, :url => {:action => 'create', :user_id => #user.id}) do |f| %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<% end %>
any ideas? Thank You
Assuming you are on rails 4, you just need to add into User.rb
has_many :user_profiles, dependent: :destroy
and into user_profile.rb
belongs_to :user
validates :user_id, presence: true
user_profiles_controller.rb
def create
#user_profile = current_user.user_profiles.build(user_profile_params)
....
end
private
def user_profile_params
params.require(:user_profile).permit(:param1, :param2)
end
form view
<%= form_for(#user_profile) do |f| %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<% end %>

using last after model included doesnt work

Im stuck (still very new to Rails), and cant figure out why its not working:
I have:
class Message < ActiveRecord::Base
attr_accessible :updated_at
has_many :categories_messages
has_many :categories, through: :categories_messages
end
class CategoriesMessage < ActiveRecord::Base
attr_accessible :category_id, :message_id
belongs_to :category
belongs_to :message
end
class Category < ActiveRecord::Base
attr_accessible :name
has_many :categories_messages
has_many :message, through: :categories_messages
end
#messagesPer = Category.all.includes(:messages).group('categories.id').order("COUNT(messages.id) DESC")
<% #messagesPer.each_with_index do |message, i| %>
<tr>
<td><%= i+1 %></td>
<td><%= message.name %></td>
<% if message.categories_messages.exists? %>
<td><%= message.messages.last.updated_at.to_s.to_date %></td>
<td><%= message.messages.first.updated_at.to_s.to_date %></td>
<td><%= message.messages.count %></td>
<% else %>
<td>0</td>
<td>0</td>
<% end %>
</tr>
<% end %>
So i want it to show :
the name of Category, date the last message was created , date first message was created, and all messages in that category.
ALl works fine, apart from the fact that it only shows the date when the first message was created, but never the last (still shows first date on the last).
What am i doing wrong?
UPDATE:
if i put
#messagesPer = Category.all.includes(:messages).group('categories.id')
it does show the right date for last and first messages but as soon as i add order it breaks...
I might be helpful to include the error information you get after adding an order clause to the query.
However, I can spot some odd things in the code. The CategoriesMessage model seems to be there simply to satisfy the condition that a category can have many messages and vice versa. You don't need a model for this many-to-many relationship though, Rails will handle this automatically for you.
Your models should be looking like this:
class Message < ActiveRecord::Base
attr_accessible :updated_at
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :messages
end
And in your database you have these tables: messages, categories,categories_messages, where the last one is the join table which only contains columns for amessage_idand acategory_id`.
Then you can simply do something like this in your code:
category.messages.each { |message| puts message.updated_at }
Also see this Ruby on Rails tutorial article for more information. If this doesn't work for you, please post the exact error you get.

Destroy action deleting from wrong table

I have a users model that can have many holidays through a rich join table.. My destroy statement on my view is deleting from the holidays table and NOT the user_holidays table as it should.. see below:
class HolidaysController < ApplicationController
def destroy
#user = User.find(params[:user_id])
#user_holiday = #user.holidays.find(params[:id])
#user_holiday.destroy
redirect_to #user
end
end
Heres the view button:
<% #user.holidays.each do |hld| %>
<td><%= hld.name %></td>
<td><%= hld.date %></td>
<td>
<%= button_to('Destroy', user_holiday_path(#user, hld), :method => 'delete', :class => 'btn btn-large btn-primary') %>
Models:
class User < ActiveRecord::Base
has_many :user_holidays
has_many :holidays, :through => :user_holidays
class UserHoliday < ActiveRecord::Base
attr_accessible :holiday_id, :user_id
belongs_to :user
belongs_to :holiday
class Holiday < ActiveRecord::Base
attr_accessible :name, :date
has_many :user_holidays
has_many :users, :through => :user_holidays
Any ideas? Thanks!!!!
You should use #user.user_holidays instead of #user.holidays
#user_holiday = #user.user_holidays.where(holiday_id: params[:id])
(my bad didn't read you question properly)
#user = User.find(params[:user_id])
#user.holidays.delete(#user.holidays.find(params[:id]))

Rails 3 with joins among 2 tables

I have 2 models, car and registrations.
class Car < ActiveRecord::Base
belongs_to :Registration
end
class Registration < ActiveRecord::Base
has_many :cars, :dependent => :destroy
accepts_nested_attributes_for :cars, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
In CarsController:
def index
#cars = Car.all
#cars2 = Car.all(:joins => :Registration)
end
In view:
<% #cars.each do |car| %>
<tr>
<td><%= car.twitter %></td>
<td><%= car.facebook %></td>
<td>
<% #cars2.Registration.each do |h| %> #here is my problem
<%= h.email %>
<% end %>
</td>
</tr>
<% end %>
This is my statement of cars. I am trying to print for every car owner's email. The email is in table Registration (model registration). I don't know how to make a query to database, that I want to get email from table Registrations, when column registration_id in table Cars == id column of table Registrations...
So I would like to ask you, if you have a tip, how to do...
You have got your associations in capital letters. It should be in small like this
class Car < ActiveRecord::Base
belongs_to :registration
end
Also you dont have to assign 2 variables in the controller
def index
#cars = Car.includes(:registration)
end
and in the view
<% #cars.each do |car| %>
<tr>
<td><%= car.twitter %></td>
<td><%= car.facebook %></td>
<td>
<%= car.registration.email %> #here is my problem
</td>
</tr>
<% end %>
Use this instead to fetch the email:
<%= car.registration.email %>
If you want eager loading, then use the following line in your controller instead:
#cars = Car.includes(:registration)
There's no need for #cars2.