Rails Association (belongs_to) dilemma - ruby-on-rails-3

I have a User model:
class User < ActiveRecord::Base
has_many :cards
end
and a Card model:
class Card< ActiveRecord::Base
belongs_to :user, :foreign_key => "owner_id"
end
the card model also has an attribute called "owner_id", which I'd like to use in way like this:
Card.first.owner which will retrieve the User which owns that card
my problem as that, I know that rails will automagically connect the id's in the association but that doesnt happen.
in the CardController, rails get stuck in the create action on the line
#card=current_user.cards.new(params[:card])
and says unknown attribute: user_id
I've done db:migrate and it still won't work.
must I do as follows for it to work?
#card = Card.new(params[:card])
#card.owner_id=current_user.id
or am I missing something?

First of all, you don't need a owner_id column for this. All you need is
class User
has_many :cards
end
This will give you #user.cards
class Card
belongs_to :owner, :class_name => "User", :foreign_key => "user_id"
end
This will give you #card.owner

Related

Uniqueness validation with a has_many relationship

My model structure is as follows:
class Client < ActiveRecord::Base
has_many :charts
end
class Chart < ActiveRecord::Base
belongs_to :client
has_many :chart_data
end
class ChartDatum < ActiveRecord::Base
belongs_to :chart
end
ChartDatum has an attribute called 'name' which needs to be unique for each client.
I tried using "validates_uniqueness_of :name, :scope => [:chart_id]" but this helped me getting a unique key for a particular chart but not for all charts for a particular client. I am looking for something like "validates_uniqueness_of :name, :scope => [:client_id]" but obviously with the current structure it will not work out.
Could someone please help me?
Since you need unique name for chart_data for each client, you can try writing a custom validation for name something like this :
class ChartDatum < ActiveRecord::Base
belongs_to :chart
validates :name, :uniqueness => true, unless => :unique_for_client?
def unique_for_client?
client = self.chart.client
client.charts.chart_data.pluck(:name).include?(self.name)
end
end

rails 3.1 model and view and controller association with 3 tables association

class Hashtag < ActiveRecord::Base
has_many :messages
end
class User < ActiveRecord::Base
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :hashtag, :foreign_key => "hashtag_id"
belongs_to :user, :foreign_key => "user_id"
end
Now if in the hashtag's show view we want to show all the messages belonging to hashtag and also an input box to create a new message.
Any kind of code examples or links or videos will be helpful ?
If the association is set up correctly, calling hashtag.messages will return an array of messages associated with that specific hashtag.
To create messages on the hashtag 'show' page you'll need to create the new message in hashtag#show.
#hashtag.messages.build
On the hashtags/show.html page, add a form for the user to edit the message. Then submit the message to message#create.

Rails 3 - model issue, foreign key

I have two models, Like and Photo.
class Like < ActiveRecord::Base
belongs_to :photo, :class_name => "DataLike", :foreign_key => "photo_id"
end
class Photo < ActiveRecord::Base
has_many :likes
end
And now I try to execute this query:
query = Like.select(:photo_id).joins(:photo).count
But I am still getting this error:
uninitialized constant Like::DataLike
Could anyone help me, please, what I am doing wrong?
Thank you so much
You don't seem to have a DataLike model, my best guess is that you want to link to the Photo model:
class Like < ActiveRecord::Base
belongs_to :photo, :foreign_key => "photo_id"
end
class Photo < ActiveRecord::Base
has_many :likes
end
If you leave out the :class_name option, the Photo model is inferred. It's used to specify the class of the linked model, in case it is different from the association name.

How do i create an object if it has more than one belongs_to?

I have the following:
class Org < ActiveRecord::Base
has_many :users
has_many :entries
end
class Entry < ActiveRecord::Base
belongs_to :org
belongs_to :user
validates_presence_of :entry_text
end
class User < ActiveRecord::Base
belongs_to :org
has_many :entries
validates_uniqueness_of :user_name
validates_presence_of :user_name, :length => { :minimum => 3 }
end
I can Create Orgs and Users... How do i create an entry if there are two belongs_to? and what is this pattern called?
Double nested resources are tricky. The trick with users usually is to keep it out of your desired entry path.
Your question is kind of broad, but if you specify more information, people would be able to help you better. Also, I would recommend using the gem Devise for your user management system. Since you're using 'users' I would assume you want users from orgs to create entries. The entry created would be a part of org and the user would be the session's current user. Sorry if I am wrong to assume this.
Your routes.rb file can look something like this (assuming rails 3):
resources :orgs do
resources :entries
end
Then the create of your entry controller would look like:
#entry = #org.entries.new(params[:topic])
#entry.user = current_user #or however you are managing the current user's session.
And you'd want to set the org for the entire class by making a method that loads your current org and do a before_filter :loadOrg
def loadOrg
#org = Org.find(params[:id])
end
This is of course assuming your path is something like: /org/(id)/entry/(entry_id)
and not
/org/(id)/user/(user_id)/entry/(entry_id)
which in my opinion is unnecessary and can lead to more problems. You can always create a userpage model that calls all entries by users, but the default route doesn't necessarily have to include users in the path.
I don't see any problem.
#entry = Entry.create(:entry_text => "Hello World!")
Now questions to clarify what do you need:
Can #entry belongs both org and user at the same time? Or it can belongs to only one of them?
Should #entry belongs to at least one of them?
If #entry supposed to belong only one of them, so you should use Polymorphism
http://railscasts.com/episodes/154-polymorphic-association
class Entry < ActiveRecord::Base
belongs_to :textable, :polymorphic => true
validates_presence_of :entry_text
end
class Org < ActiveRecord::Base
has_many :users
has_many :entries, :as => :textable
end
class User < ActiveRecord::Base
belongs_to :org
has_many :entries, :as => :textable
validates_uniqueness_of :user_name
validates_presence_of :user_name, :length => { :minimum => 3 }
end

Two has_may association with Same model Rail 3

Hi im quite beginner in rails. i have a problem suggestion will be appreciated.
i have two model "user" and "asset"
an "asset" is created by a "user" and asset" can be assigned to a "user" schema is
Asset { id,name,creator_id,assigned_to_id,price,...}
User{ id,name,....}
now in Asset model class association are
class Asset < ActiveRecord::Base
{
#validation
belongs_to :creator ,:class_name=>'User'
belongs_to :assigned_to, :class_name=>'User' ,:foreign_key=>'assigned_to_id'
}
and User Model is
class User < ActiveRecord::Base
{
#any validation and other stuff
has_many :assets #did not specify either this association is for creator , or assigned_to user.how can is specify that??
}
now in Asset show view i can obtain creator name with
#asset.creator.name
but can't assigned_to name
#asset.assigned_to.name =>(error is )undefined method `first_name' for nil:NilClas
and
#asset.assigned_to_id.name=>(error is) undefined method `first_name' for 1:Fixnum
any suggestion how can i make double association with same model
ok solution was in my last comment.
Multiple relation with same model
class Asset < ActiveRecord::Base
belongs_to :creator ,:class_name=>'User'
belongs_to :assigned_to, :class_name=>'User'
end
user.rb
class User < ActiveRecord::Base
has_many :created_assets, :foreign_key => 'creator_id', :class_name => 'Asset'
has_many :assigned_assets , :foreign_key => 'assigned_to_id', :class_name => 'Asset'
end