Where to put common code found in multiple models?
Create a module, which you can put in the lib
directory:
module Foo
def foo
# do something
end
end
You can then include
the module in each of your model classes:
class A < ActiveRecord::Base
include Foo
end
class B < ActiveRecord::Base
include Foo
end
The A
and B
models will now have a foo
method defined.
If you follow Rails naming conventions with the name of the module and the name of the file (e.g. Foo in foo.rb and FooBar in foo_bar.rb), then Rails will automatically load the file for you. Otherwise, you will need to use require_dependency 'file_name'
to load your lib file.
Is there a recommended way to use models and common files in multiple flutter projects?
The conventional approach would be put your common code in a separate Dart package (that is, a separate directory with its own pubspec.yaml
file and its source files in a lib
subdirectory). Unless you want your package to be public, there is no need to publish your package to pub.dev.
Your other projects can then add that package as a dependency in their pubspec.yaml
files. For packages not hosted on pub.dev, you probably will want to specify a local filesystem path to the package or to specify an URL to your own Git server. See the Package Dependencies documentation for more details.
Other approaches (that I don't recommend, but I mention for completeness):
- Have your projects just import common
.dart
files by relative paths. However, navigating up multiple parent directories is very ugly. - In your projects' source directories, add symlinks that refer to the common code. Then you could import common files by relative path without needing to navigate up parent directories.
- If you use separate source control repositories instead of a mono-repo, you could make each project consume common code as a Git submodule. Unlike the two approaches above, this would allow your different projects to use independent versions (the flipside is that that flexibility would be more work to maintain).
Correct way to make function available in multiple models
Use polymorphism if this models have multiple realizations of this method. However, if method universal for models, choose second.
class Product extends AbstractThumbnailedModel
{
public function setThumbnailAttribute(Thumbnail $thumb)
{
// implement setter for Product
}
}
class AnotherProduct extends AbstractThumbnailedModel
{
public function setThumbnailAttribute(Thumbnail $thumb)
{
// implement setter for AnotherProduct
}
}
abstract class AbstractThumbnailModel extends Model
{
abstract public function setThumbnailAttribute(Thumbnail $thumb);
}Use traits. Create trait Thumbnailed and use it when needed in models.
trait Thumbnailed
{
public function setThumbnailedAttribute(Thumbnail $thumb)
{
// here implementaition which will share with needed models
}
}
class Product extends Model
{
use Thumbnailed;
// Use it!
}
class AnotherProduct extends Model
{
use Thumbnailed;
// same method implementation. Just use it!
}
P.S. Sorry for Google translate
Where to put custom callbacks that I use in several models
Marek's answer is good but the Rails way is:
module NormalizeDateModule
extend ActiveSupport::Concern
included do
after_validation :normalize_date
end
def normalize_date
self.created_at = return_DateTime(created_at)
end
end
Doc here.
(and you have a decicated folder for it: models/concerns)
Flutter Scoped Model - Passing multiple Models
That is one way you can do it. I use Mixins to compile different beahviours / features into the AppModel. Each model is responsible for a section/feature in the application. As an example I have a UserModel, SettingsModel and ContentModel
They are all mixins on the Model class from the ScopedModel library
mixin UserModel on Model {
...
}
mixin SettingsModel on Model {
...
}
mixin ContentModel on Model {
...
}
And then my main AppModel looks like this
class AppModel extends Model with UserModel, SettingsModel, ContentModel {
...
}
This way I'm combining behaviours from different models, if you want to only expose the one type of model you can cast it and use that interface.
I'm curently leaning towards this way where the Model files manages all the state for certain features and in those models I inject services which are singleton instance to share information between them if needed. These services perform all my actual business logic, Connecting to the API, serializing and compiling into contextual information for my app.
Comments on multiple models
You don't want to specify each type of object that can hold Comment
objects. That creates a headache of if-elsif-else
blocks all over the place. Instead, you want things to be Commentable
, and they all will have .comments
on them.
This is called a polymorphic association in Active Record. So you would have your models something like:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
class Post < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Book < ActiveRecord::Base
has_many :comments, as: :commentable
end
And modify your database accordingly, it's all in the linked article. Now when you build a Comment
object for a form, it will have pre-populated a commentable_id
and commentable_type
, which you can toss in hidden fields. Now it doesn't matter what the Comment
is associated with, you always treat it the same.
I'd leave User
as a separate association, since it's not really the same idea.
Entity Framework 6 Code First - Multiple Model/Configurations
I have been able to solve my own question now having found a new article to refer to Multiple Model EF 6 Data points
Read the article on how to solve my question and other variants of similar problems. The key to solving this problem was to specify separate folders for each context migration when commanding the NuGet Package Manager Console. Then in the initialiser for each context, refer to the configuration in the appropriate migration folder. Rather than repeating here, please see the article on MSDN I linked to as all the information I needed was in there, plus lots more.
Multiple Models in a Single View (C# MVC3)
You should always create separate ViewModels for your views. There should be an abstraction from your Views to your Domain Models. In the demos/tutorials they show it all pretty and easy by simply strongly typing the Views to Domain Models but that's not a good strategy. The views should not be dependent on the business objects.
You should implement David Glenn's proposed solution for your current scenario and also for all other views even if requires mapping the domain model to to another view model class.
EDIT:
If you have lets say a top Menu > TopMenu.aspx
And you have multiple partial views inside it > StudentMenu.ascx
, ResultMenu.ascx
You will create a View Model for Top Menu > TopMenuViewModel.cs
And you will also create view models for partial views > StudentMenuViewModel
, ResultMenuViewModel
etc.
and your TopMenuViewModel will have both >
class TopMenuViewModel
{
//all the stuff required in TopMenu.aspx
StudentMenuViewModel studentvm;
ResultMenuViewModel resultvm;
}
and in TopMenu.aspx
when rendering the partial you will pass the relevant view model >
Html.RenderPartial('StudentView', Model.studentvm)
Hope it makes sense
Related Topics
Why Is It Best to Store a Telephone Number as a String VS. Integer
Is Rails.Cache Purged Between Tests
How to Disable Mongodb Log Messages in Console
Ruby Classes Within Classes (Or Modules Within Modules)
How to Suppress the Output of Return Value in Irb/Rails Console
Are There Good Reasons for 'Private' to Work the Way It Does in Ruby
How to Write a Web Scraper in Ruby
Using Rails to Consume Web Services/Apis
Rails: Custom Text for Rails Form_For Label
Which Gem Support Import/Export to Xlsx File in Ruby
Tzinfo-Data Present But Not Seen
What Is Mattr_Accessor in a Rails Module
Stop Rails Console from Printing Out the Object at the End of a Loop
When to Use Struct Instead of Hash in Ruby
When We Import CSV Data, How Eliminate "Invalid Byte Sequence in Utf-8"