How to save has_many :through self-referencial association - ruby-on-rails

I've set up a self-referencial association using has_many :through, basically as described on this Railscast: http://railscasts.com/episodes/163-self-referential-association.
Some "activities" act kinda like "articles" and have an associated set of other activities, hence the naming of the join table. It is a little confusing... I know.
I am having a tough time getting things to save right. Here is what I've got...
activity.rb
class Activity < ActiveRecord::Base
has_many :article_activities
has_many :activities, :through => :article_activities
accepts_nested_attributes_for :activities
end
article_activity.rb
class ArticleActivity < ActiveRecord::Base
attr_accessible :article_id, :activity_id
belongs_to :activity
belongs_to :article, :class_name => "Activity"
end
articles_controller.rb
class ArticlesController < ApplicationController
def new
#activity = Activity.new
#activity.is_article = true
#user_activities = current_user.activities
end
def create
#activity = Activity.new params[:activity]
#activity.is_article = true
#activity.user = current_user
if #activity.save
redirect_to root_path, :notice => "Article created!"
else
render :action => "new"
end
end
new.html.haml
= simple_form_for #activity, :url => articles_path do |f|
/ Other fields omitted for clarity
= f.association :activities, :collection => #user_activities
So, upon submitting the form, #activity in the create action has the expected #activity.activities. However, upon saving #activity and reloading the record, #activity.activities is empty.
Any ideas how to save the associations?

I figured this one out. I had to add a :foreign_key for "article" to the models...
class ArticleActivity < ActiveRecord::Base
attr_accessible :article_id, :activity_id
belongs_to :activity
belongs_to :article, :class_name => "Activity", :foreign_key => "article_id"
end
class Activity < ActiveRecord::Base
belongs_to :user
has_many :article_activities, :foreign_key => "article_id"
has_many :activities, :through => :article_activities
end

Related

Cannot save check_box_tag data with has_many through

I am trying to save checkbox data in project table
In Project Controller
def new
#project = Project.new
#allTags = Tag.all
#allBenefits = Benefit.all
end
def create
p params[:projectName]; # this always throws nil even there is a value
#project = Project.new(project_params)
##tagging = #project.tagging.create!(:project=>Project.id,:tag=>1)
if #project.save
redirect_to :action => 'index'
else
render :action => 'new'
end
end
def project_params
params.require(:com_a_b_c_project).permit(:projectName, :briefDesc, :whatSection, :challengers, :status, :valueProposal, :maturityLevel,:tag_ids =>[])
end
In Project new view
<h4><label for = "tags">Tags</label></h4>
<% #allTags.each do |tag| %>
<p><%= f.label tag.tagName %></p>
<%= check_box_tag :tag_ids, tag.id, #project.tags.include?(tag), :name => 'project[tag_ids][]'-%>
<%end%>
class Com::a::b::c::Project < ActiveRecord::Base
has_many :taggings
has_many :tags, :through => :taggings
accepts_nested_attributes_for :tags
end
class Com::a::b::c::Tag < ActiveRecord::Base
has_many :taggings
has_many :projects, :through => :taggings
end
class Com::a::b::c::Tagging < ActiveRecord::Base
belongs_to :project
belongs_to :tag
end
On my logs I get tag_ids parameter as below
project"=>{"tag_ids"=>["1", "2"]}
Q. Do I have to save data to Tagging table separately or does it automatically saves data because of the associations in the table?
Currently nothing get saved on the tagging table. How can I store tagging data?
if i follow correctly
class Com::a::b::c::Project < ActiveRecord::Base
has_many :taggings
has_many :tags, :through => :taggings
accepts_nested_attributes_for :tags
end
on project model should allow this to be persisted.

polymorphic association belongs to User

I have a comments model which is a polymorphic association which is involved with Statuses and Photos. How can I create this polymorphic association to also belong to a User so that when a user creates a comment under statuses or photos it will also recieve the current_user id?
this is what I have as of now-
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :user
end
class User < ActiveRecord::Base
has_many :comments
end
class Status < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Photo < ActiveRecord::Base
has_many :comments, as: :commentable
end
just to reiterate, how can I create a comment as a user but also have it under status or photo? it would need the user_id.
This is where I am having the trouble-
how should I set this up?
def create
#comment = #commentable.comments.new(comments_params)
if #comment.save
redirect_to #commentable, notice: "Comment created"
else
render :new
end
end
Try this
class Comment < ActiveRecord::Base
belongs_to :likable, :polymorphic => true
belongs_to :commentable, :polymorphic => true
belongs_to: user
class User < ActiveRecord::Base
has_many :statuses, :as => :likable
has_many :photos, :as => :commentable
has_many :comments
class Status < ActiveRecord::Base
has_many :comments, :as => :likable, :dependent => :destroy
class Photos < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
It's a little bit hacky but I found a workaround. So in my CommentsController i did this:
def create
new_params = comments_params
new_params[:user_id] = current_user.id
#comment = #commentable.comments.build(new_params)
if #comment.save
redirect_to #commentable, notice: "Comment created"
else
render :new
end
end
that placed the user_id which is what I needed.

rails belongs_to foreign key is null

i have the following models
class User
has_many :projects, :through => :bids
has_many :bids, :dependent => :destroy
end
class Project
attr_accessible :name, :user_id
has_many :users, :through => :bids
has_many :bids, :dependent => :destroy
belongs_to :projectmanager, :class_name => "User", :foreign_key => "user_id"
end
class Bid
attr_accessible :project_id, user_id
belongs_to :user
belongs_to :project
end
As you can see, my Project class has both *has_many* and *belongs_to* to the same model (User)
In Project controller new I have
def new
#project = Project.new
#project.gencontr = current_user
where current_user is Devise current logged in user.
When I save the project, the column user_id in the Projects table is always null. Can you show me where do I go wrong on this one...Thank you
on create action
def create
#project = Project.new(prams[:project])
#project.projectmanager = current_user
.......
end

Rails 3.2 Nested Form Custom Foreign Key Unable to Save

I have this Reviews Model:
class Review < ActiveRecord::Base
attr_accessible :approved, :reviewed_id, :for, :user_id, :text, :rating, :title
belongs_to :business
belongs_to :product
end
and this Product model:
class Product < ActiveRecord::Base
include ApplicationHelper
belongs_to :business
belongs_to :catalog
belongs_to :category
has_many :reviews, :foreign_key => :reviewed_id
has_many :features, :dependent => :destroy
end
and this Business model:
class Business < ActiveRecord::Base
validates_presence_of :name
validates_presence_of :category
mount_uploader :photo, PhotoUploader
has_many :catalogs, :dependent => :destroy
has_many :products, :dependent => :destroy
has_many :branches, :dependent => :destroy
has_many :reviews, :foreign_key => :reviewed_id
end
but with this create action in the Reviews controller:
def create
#business = Business.find(params[:business_id])
if params.has_key?('product_id')
#product = Product.find(params[:product_id])
#review = #product.reviews.build(params[:review])
if #review.save
flash[:notice] = 'Pending Review Submitted'
redirect_to business_product_path(#business, #product)
else
#form_resources = [#business, #product, #review]
respond_with(#business, #product, #review)
end
else
#review = #business.reviews.build(params[:review])
if #review.save
flash[:notice] = 'Pending Review Submitted'
redirect_to business_path(#business)
else
#form_resources = [#business, #review]
respond_with(#business, #review)
end
end
end
I can't save the association. simple_form says there is an error, but I can't see the error in my logs, and all the other fields are validated so I'm guessing there is a problem with the association.
SIDE QUESTION: how can you I make simple_form show all errors?
fixed it by using polymorphic associations and getting rid of for and reviewed_id in the reviews model. refer here:
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

Nested Forms not passing belongs_to :id

I have the following model
class Project < ActiveRecord::Base
has_many :assignments, :conditions => {:deleted_at => nil}
has_many :members, :conditions => {:deleted_at => nil}
accepts_nested_attributes_for :members, :allow_destroy => true
end
class Member < ActiveRecord::Base
belongs_to :project
belongs_to :person
belongs_to :role
has_many :assignments, :dependent => :destroy, :conditions => {:deleted_at => nil}
accepts_nested_attributes_for :assignments, :allow_destroy => true
validates_presence_of :role_id
validates_presence_of :project_id
end
and I assume the controller will populate the member.project_id upon project.save for each nested member record. However, I get a validation error stating the project_id is blank.
My controller method:
def create
# #project is created in before_filter
if #project.save
flash[:notice] = "Successfully created project."
redirect_to #project
else
render :action => 'new'
end
end
Do I need to manually set the project_id in each nested member record? Or what is necessary for the controller to populate when it creates the member records?
Create the Member object like this:
#member = #project.members.build

Resources