Get count of likes on a post in Rails - html

In my rails application, I am using the gem, socialization.
I just can't figure out how to display the amount of likes!
My post controller :
class PostsController < ApplicationController
# GET /posts
# GET /posts.json
def index
#posts = Post.all(:order => "created_at DESC")
#posts_not_signed_in = Post.all(:order => "created_at DESC")
#post = Post.new
#users = User.all(:order => "created_at DESC")
respond_to do |format|
format.html # index.html.erb
format.json { render json: #posts }
end
end
def like
post.liked_by current_user
redirect_to root_path
end
# GET /posts/1
# GET /posts/1.json
def show
redirect_to posts_path
end
# GET /posts/new
# GET /posts/new.json
def new
#post = Post.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #post }
end
end
# GET /posts/1/edit
def edit
#post = Post.find(params[:id])
end
# POST /posts
# POST /posts.json
def create
#post = current_user.posts.build(params[:post])
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render json: #post, status: :created, location: #post }
else
format.html { render action: "new" }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# PUT /posts/1
# PUT /posts/1.json
def update
#post = Post.find(params[:id])
respond_to do |format|
if #post.update_attributes(params[:post])
format.html { redirect_to #post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
#post = Post.find(params[:id])
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
end
My user controller :
class UsersController < ApplicationController
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
end
def show
#user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
def follow
#user = User.find(params[:id])
current_user.toggle_follow!(params[:id])
redirect_to root_path
end
def unfollow
#user = User.find(params[:id])
current_user.stop_following(#user)
redirect_to root_path
end
end
My post model :
class Post < ActiveRecord::Base
attr_accessible :status, :author, :username, :id, :user_id, :user, :website, :bio, :skype, :dob, :age, :email, :motto, :follower, :followable, :votes
belongs_to :user
has_many :like
has_many :likes
validates :status, :presence => true
acts_as_likeable
acts_as_votable
end
My user model :
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :user_id, :id, :website, :bio, :skype, :dob, :age, :motto, :follower, :followable
has_many :posts
acts_as_liker
# attr_accessible :title, :body
end
My view :
<% if user_signed_in? %>
<h1 id="welcome" class="nuvo">Welcome <%= current_user.username %>!</h1>
<% else %>
<h1 id="welcome" class="nuvo">Log-In to make some posts!</h1>
<% end%>
<div class="follow-row">
<div class="titan-users nuvo"><h2>BoomIt Users</h2></div>
<div class="user-row nuvo"><%= link_to 'coreypizzle', user_path(1) %> - <%= link_to 'BoomBoard', dashboard_path(1) %></div>
<% #users.each do |user| %>
<div class="user-row nuvo"><%= link_to user.username, user_path(user.id) %> - <%= link_to 'BoomBoard', dashboard_path(user.id) %></div>
<% end %>
</div>
<div class="statuses">
<% if user_signed_in? %><div class="status-form"><%= render 'form' %></div><% end %>
<% if user_signed_in? %>
<% #posts.each do |post| %>
<div class="post">
<div class="tstamp">
<%= image_tag avatar_url_small(post.user), :class => 'gravatar' %>
<strong>Posted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.username %></strong>
</div>
<div class="status"><%= post.status %></div>
<div class="likearea"><%= link_to 'BoomThis', 'posts/like', :class => 'wtxt nuvo' %> - <%= #post.likes.size %></div>
</div>
<% end %>
<% else %>
<% #posts_not_signed_in.each do |post| %>
<div class="post">
<div class="tstamp">
<%= image_tag avatar_url_small(post.user), :class => 'gravatar' %>
<strong>Posted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.username %></strong>
</div>
<div class="status"><%= post.status %></div>
</div>
<% end %>
<% end %>
</div>
Any help would be greatly appreciated!

First
has_many :like
has_many :likes
I think you mean just
has_many :likes
So you would do
#likes_num = #post.likes.count
Which will create a query for the number of likes, and not the actually likes themselves.

Old question, but i couldn't find this either.
The correct method call appears to be:
post.likers(User).count
I'm still unsure why you have to pass the model name in, perhaps so you can ask for the number of likes from that class of liker?
This works though.

Related

Ruby on Rails Form & View on the same page

On my homepage there is an account creation (users) form, a submission form for designs (designs), and I'm trying to add a section on the same page where users can view active designs and vote on them. I'm having problems adding that section to the page because of the submission form I think - here are the relevant files:
landing-controller (homepage controller)
class LandingController < ApplicationController
def index
#email = Email.new
#design = Design.all
#user = User.new
end
end
When I change #design to Design.new it works for the submission and not the view.
designs-controller
class DesignsController < ApplicationController
protect_from_forgery with: :exception
before_filter :admin_user, only: [:show ,:edit, :update, :destroy]
def show
#design = Design.find(params[:id])
end
def edit
#design = Design.find(params[:id])
end
def new
#design = Design.new
end
def create
#design = Design.new(design_params)
respond_to do |format|
if #design.save
format.html { redirect_to root_path, notice: 'Thank You For Your Submission!' }
format.json { render json: Design.create(design_params) }
else
#user = User.new
format.html { render "landing/index" }
format.json { render :json => #design.errors, :status => :unprocessable_entity }
end
end
end
def update
#design = Design.find(params[:id])
if #design.update(design_params)
redirect_to '/cpanel'
else
render 'edit'
end
end
def destroy
#design = Design.find(params[:id])
#design.destroy
redirect_to '/cpanel'
end
private
def design_params
params.require(:design).permit(:dfirstname, :dlastname, :demail, :rcode, :frontview, :sideview, :backview, :category, :active)
end
def admin_user
redirect_to(root_path) unless current_user && current_user.admin?
end
end
Then I have this in the landing view:
<% #design.each do |design| %>
<% if design.active %>
<%= image_tag design.frontview, :class => 'design-image' %>
<% else %>
<% end %>
<% end %>
and this below it
<%= form_for #design.new, url: designs_path, html: {class: "design-form", :multipart => true} do |f| %>
<h2>Design Submission</h2>
<% if #design.new.errors.any? %>
<ul>
<% #design.errors.full_messages.each do |message| %>
<li class="e-message">- <%= message %></li>
<% end %>
</ul>
<% end %>
... form ...
<% end %>
Basically getting these to work together, as of right now it will load the page, but then give me an error message when I try to submit the form. The specific error message is undefined method each in the landing index page.
You can't use #design in the form as you defined as #design = Design.all. You should change #design = Design.all to #designs = Design.all and add #design = Design.new in the index method
class LandingController < ApplicationController
def index
#email = Email.new
#designs = Design.all
#design = Design.new
#user = User.new
end
end
And also change
<% #design.each do |design| %>
to
<% #designs.each do |design| %>
and
<%= form_for #design.new, url: designs_path, html: {class: "design-form", :multipart => true} do |f| %>
to
<%= form_for #design, url: designs_path, html: {class: "design-form", :multipart => true} do |f| %>
in the view page.
Update:
As per our discussion and the code of the design_controller.rb, in the create method in the else block you should have #designs = Design.all because if the creation is failed you are rendering index.html.erb with this code format.html { render "landing/index" }, so Rails doesn't know where #designs come from in this case.
def create
#design = Design.new(design_params)
respond_to do |format|
if #design.save
format.html { redirect_to root_path, notice: 'Thank You For Your Submission!' }
format.json { render json: Design.create(design_params) }
else
#user = User.new
#designs = Design.all
format.html { render "landing/index" }
format.json { render :json => #design.errors, :status => :unprocessable_entity }
end
end
end

NoMethodError in CommentsController#new undefined method `text' for #<Comment id: nil, author: nil, created_at: nil, updated_at: nil>

I'm trying to use rails with react, just by adding a comments section to the app i'm working on. The /comments page works. But when I try to make a new comment. I get this error. I went back to the guide I'm using and doesn't explain anything about this. I'm new to rails and react so if someone could help me out I would appreciate it.
Application Trace:
app/views/comments/_form.html.erb:20:in `block in_app_views_comments__form_html_erb__930297241_104622300'
app/views/comments/_form.html.erb:1:in `_app_views_comments__form_html_erb__930297241_104622300'
app/views/comments/new.html.erb:3:in `_app_views_comments_new_html_erb__151456299_104688260'
comments_controller.rb:
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
def index
#comments = Comment.all
end
# GET /comments/1
# GET /comments/1.json
def show
end
# GET /comments/new
def new
#comment = Comment.new
end
# GET /comments/1/edit
def edit
end
# POST /comments
# POST /comments.json
def create
#comment = Comment.new(comment_params)
respond_to do |format|
if #comment.save
format.html { redirect_to #comment, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: #comment }
else
format.html { render :new }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
respond_to do |format|
if #comment.update(comment_params)
format.html { redirect_to #comment, notice: 'Comment was successfully updated.' }
format.json { render :show, status: :ok, location: #comment }
else
format.html { render :edit }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
#comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
#comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:author, :comment_text)
end
end
_form.html.erb:
<%= form_for(#comment) do |f| %>
<% if #comment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#comment.errors.count, "error") %> prohibited this comment from being saved:</h2>
<ul>
<% #comment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :author %><br>
<%= f.text_field :author %>
</div>
<div class="field">
<%= f.label :comment_text %><br>
<%= f.text_area :comment_text %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
new.html.erb:
<h1>New Comment</h1>
<%= render 'form' %>
<%= link_to 'Back', comments_path %>
[timestamp]_create_comments.rb:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :author
t.text :comment_text
t.timestamps null: false
end
end
end
Seems like the problem originates with your schema/migration. The line:
params.require(:comment).permit(:author, :text)
suggests that you have a column named text, which is a datatype in Rails. You should pick a name like "comment_text" for that column that doesn't echo the name of a datatype.
It's also possible that you transposed the datatype and the column name in your migration.

Rails 4.1: Unable to create multiple answers in form

Want to create a polling app that allows you to create a question with 5 different possible answers (multiple choice).
The user can create a question via the question_form.html.erb followed by possible answers but it only shows me one box , not five.
question_form.html.erb
<%= form_for([ #poll, #question ]) do |f| %>
<% if #question.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#question.errors.count, "error") %> prohibited this question from being saved:</h2>
<ul>
<% #question.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :kind %><br>
<% #kind_options.each do |option| %>
<label>
<%= f.radio_button :kind, option[1] %>
<%= option[0] %>
</label>
<% end %>
<p>Specify some choices:</p>
<%= f.fields_for :possible_answers do |c| %>
<p>
<%= c.text_field :title, placeholder: "Type your choice", class: "form-control" %>
</p>
<% end %>
</div>
in my questions controller I have added line 5.times { #question.possible_answers.build }
but when i run the program it gives me 1 box to enter the answer not 5?
<div class="actions">
<%= f.submit 'Save', class: "btn btn-primary" %>
</div>
<% end %>
class QuestionsController < ApplicationController
before_action :set_question, only: [:show, :edit, :update, :destroy]
before_action :set_poll
before_action :set_kind_questions
# GET /questions
# GET /questions.json
def index
#questions = Question.all
end
# GET /questions/1
# GET /questions/1.json
def show
end
**# GET /questions/new
def new
#question = #poll.questions.build
5.times { #question.possible_answers.build }
end**
# GET /questions/1/edit
def edit
end
# POST /questions
# POST /questions.json
def create
#question = #poll.questions.build(question_params)
respond_to do |format|
if #question.save
format.html { redirect_to #poll, notice: 'Question was successfully created.' }
format.json { render :show, status: :created, location: #question }
else
format.html { render :new }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /questions/1
# PATCH/PUT /questions/1.json
def update
respond_to do |format|
if #question.update(question_params)
format.html { redirect_to #question, notice: 'Question was successfully updated.' }
format.json { render :show, status: :ok, location: #question }
else
format.html { render :edit }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# DELETE /questions/1
# DELETE /questions/1.json
def destroy
#question.destroy
respond_to do |format|
format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_question
#question = Question.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def question_params
params.require(:question).permit(:title, :kind, :poll_id)
end
**def set_kind_questions
#kind_options = [
[ "Open Answer", "open" ],
[ "Multiple Choice", "choice" ],
]
end**
def set_poll
#poll = Poll.find params[:poll_id] #/polls/1/questions
end
end
If you're working through Build a Polling Application with Rails, the Question model you're most likely using (which you didn't list) is incomplete, so Rails chokes on possible_answers before the controller's Questions#new iterates through the build method. You need to add accepts_nested_attributes_for :possible_answers to the model. Then 5.times { #question.possible_answers.build } will work.
app/models/question.rb
class Question < ActiveRecord::Base
belongs_to :poll
has_many :possible_answers
accepts_nested_attributes_for :possible_answers
end
I've run into a few snags where the author edited code out of sync with his screencasts. You have to look carefully at the diffs on his tut's repo.

No route matches {:action=>"search", :controller=>"devise/index"}

I'm having a problem with my research routes. they accuse this error:
ActionController::UrlGenerationError in Devise::Sessions#new
No route matches {:action=>"search", :controller=>"devise/index"}
my application:
<!DOCTYPE html>
<html>
<head>
<title>Javendi</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div class = 'search', style="display:none">
<%= form_for root_path, :url => {:action => 'search', :controller=>"index"} do |f|%>
<%= text_field_tag "ad[price_min]", #ads_min, :placeholder => 'Price min', class: 'price' %>
<%= text_field_tag "ad[price_max]", #ads_max, :placeholder => 'Price max', class: 'price' %><br>
<%= text_field_tag "ad[title]", #ads_text, :placeholder => 'Ad name', class: 'titlesearch' %><br>
<div class='categorysearch'>
<%= collection_select :ad, :category_id, Category.all,:id,:name,:prompt => true, :selected => #ads_category_id %>
<br></div>
<%= f.submit'Searc', class: 'bottomsearch' %>
<%end%>
</div>
<div class="cima">
<!-- <img src="assets/2.gif" border="0" onmouseover="this.src='assets/7.gif'" onmouseout="this.src='assets/2.gif'"> -->
<div class= 'logout'>
<% if user_signed_in? %>
<%= link_to image_tag('exit.png', width: '50px', height:'50px'),destroy_user_session_path, method: :delete %>
<%else%>
<%end%>
</div>
<div class= "home">
<%= link_to image_tag('logo.png'),root_path %>
</div>
<div class="javendi">
<% if user_signed_in? %>
<button class= 'botton1'>
<%= link_to 'Editar Perfil', edit_user_registration_path %>|
<%= link_to 'Novo AnĂșncio', new_ad_path %>|
<%= link_to 'Meus AnĂșncios', my_ads_path %>|
<%= link_to 'Meus Favoritos', fav_ads_path %>
</button>
<%else%>
<button class= 'botton'>
<%= link_to 'Cadastre-se', new_user_registration_path %> |
<%= link_to 'Login', new_user_session_path %>
</button>
<%end%>
<div class='triangule'>
<div class="seta-cima">
</div>
</div>
</div>
<% if user_signed_in? %>
<div id='iconsearh2'>
<%= image_tag("search.png") %>
</div>
<%else%>
<div id='iconsearh'>
<%= image_tag("search.png") %>
</div>
<%end%>
</div>
<script type="text/javascript">
$('#iconsearh').click(function(){
if($('.search').is(':visible')){
$('.search').slideUp('fast')
$('.seta-cima').css("display","none");
}else{
$('.search').slideDown('fast')
$('.seta-cima').show();
}
});
</script>
<script type="text/javascript">
$('#iconsearh2').click(function(){
if($('.search').is(':visible')){
$('.search').slideUp('fast')
$('.seta-cima').css("display","none");
}else{
$('.search').slideDown('fast')
$('.seta-cima').show();
}
});
</script>
<div class='cima2'>
<div class='welcome'>
<% if current_user.present?%>
welcome <%=current_user.name%>
<%end%>
</div>
<div class= 'createad'>
<%= image_tag('7.gif', width: '50px', height:'50px')%>
</div>
</div>
<div class="results">
<%= yield %>
</div>
<div class= "bot">
&nbsp
</div>
</div>
</body>
</html>
my ads model:
class Ad < ActiveRecord::Base
validates_presence_of :title, message: "deve ser preenchido"
validates_presence_of :price, message: "deve ser preenchido"
validates_presence_of :adress, message: "deve ser preenchido"
validates_presence_of :email, message: "deve ser preenchido"
validates_presence_of :phone, message: "deve ser preenchido"
belongs_to :user
belongs_to :category
has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos, :allow_destroy => true
has_many :user_ad_favs
def can_edit?(current_user)
if current_user.present?
return current_user.id == self.user_id
end
end
def self.search(query)
category = query[:category_id].present? ? "category_id = #{query[:category_id]}" : nil
title = query[:title].present? ? "title LIKE '%#{query[:title]}%'" : nil
price_min = query[:price_min].present? ? "price >= #{query[:price_min].to_f}" : nil
price_max = query[:price_max].present? ? "price <= #{query[:price_max].to_f}" : nil
query = [category, title, price_min, price_max].compact.join(" AND ")
return Ad.where ( query )
end
def user_fav(user)
return self.user_ad_favs.find_by_user_id_and_ad_id(user.id, self.id)
end
end
my ads controller:
class AdsController < ApplicationController
before_action :set_ad, only: [:show, :edit, :update, :destroy, :fav_ad,:unfav_ad, :search,]
# GET /ads
# GET /ads.json
def index
#ads = Ad.all
end
# GET /ads/1
# GET /ads/1.json
def show
end
# GET /ads/new
def new
#ad = current_user.ads.build
1.times { #ad.photos.build}
end
# GET /ads/1/edit
def edit
end
def search
#ads_min = params[:ad][:price_min]
#ads_max = params[:ad][:price_max]
#ads_title = params[:ad][:title]
#ads_category_id = params[:ad][:category_id]
#ads = Ad.search(params[:ad])
render :action => 'index'
end
# POST /ads
# POST /ads.json
def create
#ad = current_user.ads.build(ad_params)
respond_to do |format|
if #ad.save
format.html { redirect_to #ad, notice: 'Ad was successfully created.' }
format.json { render :show, status: :created, location: #ad }
else
format.html { render :new }
format.json { render json: #ad.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /ads/1
# PATCH/PUT /ads/1.json
def update
respond_to do |format|
if #ad.update(ad_params)
format.html { redirect_to #ad, notice: 'Ad was successfully updated.' }
format.json { render :show, status: :ok, location: #ad }
else
format.html { render :edit }
format.json { render json: #ad.errors, status: :unprocessable_entity }
end
end
end
# DELETE /ads/1
# DELETE /ads/1.json
def destroy
#ad.destroy
respond_to do |format|
format.html { redirect_to ads_url, notice: 'Ad was successfully destroyed.' }
format.json { head :no_content }
end
end
def fav_ad
user_ad_fav = #ad.user_fav(current_user)
if user_ad_fav.present?
user_ad_fav.update_attribute(:fav, true)
else
#ad.user_ad_favs.create(:user_id => current_user.id,:ad_id => #ad.id,:fav => true)
end
respond_to do |format|
format.js {render inline: "location.reload();"}
end
end
def unfav_ad
#ad.user_fav(current_user).update_attribute(:fav, false) if #ad.user_fav(current_user).present?
respond_to do |format|
format.js {render inline: "location.reload();"}
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_ad
#ad = Ad.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def ad_params
params.require(:ad).permit(:title, :price, :adress, :city, :state, :description, :email, :phone, :phone_type, :category_id, :photos_attributes =>[:photo])
end
end
You made a mistake in the :controller parameter in your form_for:
<%= form_for root_path, :url => {:action => 'search', :controller=>"index"} do |f|%>
First of all, the :controller should be 'ads' since the search action is in the AdsController you provided a sample of.
Second, you're using form_for wrong. You're passing in two different paths, root_path and the :url hash. The first parameter should be the model you're trying to make a form for. But you don't need that here, you just want a search form, so use form_tag instead:
<%= form_tag :action => 'search', :controller=>"ads" do %>
http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag

Many to Many table collection_select error

I am trying to have rails populate an inbetween table. The inbetween table is: room_task
The form I am using is the new task form, which is nested.
Here is the model:
class Property < ActiveRecord::Base (property is parent nest)
attr_accessible :brand_id, :name, :user_property_code, :total_rooms, :property_addresses_attributes
belongs_to :brand
has_many :rooms
has_many :nonrooms
end
class Room < ActiveRecord::Base (room)
attr_accessible :number, :out_of_order, :property_id, :room_type_id, :taskable_id
belongs_to :room_type
belongs_to :property
has_many :room_tasks
has_many :tasks, through: :room_tasks
accepts_nested_attributes_for :tasks
accepts_nested_attributes_for :room_tasks
#add_index :room, :property_id
end
class Room < ActiveRecord::Base (task)
attr_accessible :number, :out_of_order, :property_id, :room_type_id, :taskable_id
belongs_to :room_type
belongs_to :property
has_many :room_tasks
has_many :tasks, through: :room_tasks
accepts_nested_attributes_for :tasks
accepts_nested_attributes_for :room_tasks
#add_index :room, :property_id
end
class RoomTask < ActiveRecord::Base (in between table)
attr_accessible :room_id, :task_id
has_one :room
has_one :task
belongs_to :room # foreign key - room id
belongs_to :task # foreign key - task id
end
Controller (task - where I want to create the new task and also the required relationship in the inbetween table)
class TasksController < ApplicationController
before_filter :find_property
def find_property
#property = Property.find(params[:property_id])
#room = #property.rooms
end
# GET /tasks
# GET /tasks.json
def index
#tasks = Task.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #tasks }
end
end
# GET /tasks/1
# GET /tasks/1.json
def show
#task = Task.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #task }
end
end
# GET /tasks/new
# GET /tasks/new.json
def new
#task = Task.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #task }
end
end
# GET /tasks/1/edit
def edit
#task = Task.find(params[:id])
end
# POST /tasks
# POST /tasks.json
def create
#task = Task.new(params[:task])
#task.time_assigned = Time.now
respond_to do |format|
if #task.save
format.html { redirect_to property_tasks_path(#property), notice: 'Task was successfully created.' }
format.json { render json: #task, status: :created, location: #task }
else
format.html { render action: "new" }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# PUT /tasks/1
# PUT /tasks/1.json
def update
#task = Task.find(params[:id])
respond_to do |format|
if #task.update_attributes(params[:task])
format.html { redirect_to #task, notice: 'Task was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tasks/1
# DELETE /tasks/1.json
def destroy
#task = Task.find(params[:id])
#task.destroy
respond_to do |format|
format.html { redirect_to tasks_url }
format.json { head :no_content }
end
end
end
Form (using a collection select (purpose would be to select the room of the property that the task is tied to and populate in the inbetween table)
<%= form_for([#property, #task]) do |f| %>
<% if #task.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#task.errors.count, "error") %> prohibited this task from being saved:</h2>
<ul>
<% #task.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div>
<%= fields_for(:room_task) do |t| %>
<%= collection_select(:room_task, :room_id, #room, :id, :number) %> #without t. works but does not assign
<% end %>
<%= #room %> #debug collection pull - good
<div class="actions">
<%= f.submit %>
</div>
<% end %>
So I need help on ensuring that my inbetween table is populated when selecting the room. When f. or t. is prefixed to the collection_select, rails throws errors.
I am extremely confused. Help would be greatly appreciated, please let me know if any additional information is needed.
receiving this error when adding f. or t.
undefined method `merge' for :number:Symbol
displays and works fine without f. or t. but does not populate table.