How to access a foreign key field in a sqlite model? - sql

I'm working in an auction web app in Django. I'm designing the database and would like to reference the username attribute from User() model in my Listing() model.
class User(AbstractUser):
pass
class Listing(models.Model):
## some fields
owner = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="listing")
def __str__(self):
return f"Owner: #{self.owner.username}"
The User class, in AbstractUser there is a username field, i checked. But somehow I'm getting this error:
'ManyRelatedManager' object has no attribute 'username'

Related

Yii HAS_ONE relation doesn't save foreign key

I have a problem with HAS_ONE relation in Yii framework. The scenario is as follow:
We have a User class with relation to SubscriptionType:
'subscriptionType' => array(self::HAS_ONE, 'SubscriptionType', 'subscription_type_id')
And s SubscriptioType with relation to User:
'users' => array(self::HAS_MANY, 'User', 'subscription_type_id')
What is more, User has a Foreign Key to SubscriptionType defined in the database.
There are 3 subscription types predefined and all the registering users get one of them by default during the registration. They are saved in the DB, so in the registerAction I do:
//some assignments here
$subscription = SubscriptionType::model()->find('name=:name', array(':name'=>SubscriptionType::MONTHLY));
$newUser->subscriptionType = $subscription;
if($newUser->save()){
//redirect to some page
} else {
Yii::trace('User register failed', 'application.controllers.UserController');
}
The user don't get saved. I debuged it bit and I noticed, that subscriptionType is assigned but subscription_type_id is not, so the INSERT query is throwing the constraint violation.
Do I have to set the subscription_type_id explicitly? It doesnt make to much sense to me because it's against the idea of ORM, isnt' it?
I think you are defining the relations incorrectly. HAS_ONE is for the Parent side of a One-to-One relationship, and HAS_MANY is for the Parent side of a One-to-Many relationship. You need a BELONGS_TO on one of these which should be on the child side of the relationship. I am guessing that you user model should have the BELONGS_TO like this:
'subscriptionType' => array(self::BELONGS_TO, 'SubscriptionType', 'subscription_type_id')
The other issue you are having is that you are trying to assign a value to subscripionType when it is more like a read only attribute in that it is populated by the framework. In the case of a HAS_ONE, or a BELONGS_TO, this will be a CActiveRecord model. In the case of a HAS_MANY or MANY_TO_MANY, it will be an array of CActiveRecord models. These models are not saved when you save the parent model. However since they are indeed models, you can update and save these individual child models.

Kohana 3.x ORM has_many through delete relationship

I Have three tables, contact, list and listmembers. Contacts from contact table are associated to lists from list table via listmembers table.
class Model_Contact extends ORM{
protected $_has_many = array(
'lists'=>array('model'=>'List', 'through'=>'listmembers', 'far_key'=>'dlid', 'foreign_key'=>'uid')
);
}
class Model_List extends ORM
{
protected $_has_many = array(
'contacts'=>array('model'=>'Contact', 'through'=>'listmembers', 'far_key'=>'uid', 'foreign_key'=>'dlid')
);
}
I have to update contact and list relationship in listmemebers table
- create new relationship between existing contact and existing list
- Remove relationship between contact and list
How can I achieve this in Kohana ORM? I can always create model for listmembers and directly add/delete on this model. But is there a way to handle via relationship without creating listmembers model?
I think the documentation explains it quite well: http://kohanaframework.org/3.2/guide/orm/relationships#hasmany-through

How to make an object an attribute of another object in rails

Is there a way to make a Rails model have another model as an attribute?
E.g. I have a User model with an address attribute, and the address attribute in the User model is its own class.
User Model
----------
lastName:string
firstname:string
address: addressModel
Address Model
-------------
street: string
city:string
zipCode:integer
Yes, you can use associations for that:
class User < ActiveRecord::Base
has_one :address
end
class Address < ActiveRecord::Base
belongs_to :user
end
Note that for this to work you need to have a user_id field in your addresses table.
This will magically give your user object an address attribute of type Address. It also allows you to assign an address to a user. E.g.:
address = Address.find(1)
user = User.find(1)
user.address = address
user.save
user.address.class # => Address
user.address.id # => 1
This is an example of a 1:1 association between user and address. Check the guide I linked to above for explanations about other types of association.

How do I able to create a user before initialization of model

In my model(Product) i have a validation, that each product should have a valid owner (login_id of user)
validates_presence_of :owner
validates_inclusion_of :owner, :in => User.first.login_id, :message => "%{value} is not a valid owner name"
I am trying to create product mock object using factory girl
for creating a new product I need login_id of a user.
to do so i have create a user.
up to this every thing is ok, but when i am trying to create a Product using that user's login_id
product is not create, and displaying validation message ("User1 is not a valid owner name").
After digging into deeper i found that
Problem arise from validation in my model.
I have a validation (validates_inclusion_of :owner, :in => User.first.login_id) which initialize before creating the mock user in factory.rb,
(up to that time no user is created in database, user is created after initialization of model when it execute factory.rd )
My question is:
1. How do I able to create a user before initialization of model.
Can you not create a user object, and then pass that object to your product factory? This should create a valid user and then supply it through the owner association and make the product valid.
user = Factory(:user, :name => "User1")
product = Factory(:product, :owner => user)
This user apparently has to be the first user too? So if you have existing user objects then you can try clearing all users before you create the first one.
User.delete_all
I solve this problem as follows:
In my model I have replaced the 'Rails validation' by writing Custom validation method. This custom validation method will be called at the time of creating 'Product'.
validates_presence_of :owner
validate :owner_should_be_registered_user
def owner_should_be_registered_user
if !User.all_user.include? owner and !owner.nil?
errors.add(:owner, "is not a valid user")
end
end

How to access devise current_user from model

Just start to develop with devise for my app authentication, however running into trouble with accessing current_user from a model. I have no problem accessing this from a controller.
For my scenario I need to get the current user id to keep track who has edit the blog post, which I save the user id with before_save filter.
Appreciate your help!
Thanks
You can only pass it down in a parameter.
class SomeModel
def my_nifty_method(user)
end
end
in controller:
class SomeModelsController < ApplicationController
def some_method
sm = SomeModel.new
sm.my_nifty_method(current_user)
end
end
You should be able to do this in your model. 'c' here being the model object and setting it's user_id attribute before create, or save in your case.
before_create {|c| c.user_id = Authorization.current_user.id}
I'm somewhat new to RoR so be warned.
Why are you trying to access to that method in the model?
You can access to the ID attributes via self.id (within the model)