Basic example:
1) I create a new rails project with following instruction:
rails new tut3
2) I generate my first scaffold model costumer
rails generate scaffold costumer name:string
3) I generate my second scaffold model product
rails generate scaffold product item:string costumer_id:integer
4) I run the migration (rake db:migrate) and after starting the server (rails s)
and adding a few costumers (e.g. Mario, Anna etc..) I go to the products page and I expected to get a costumer field with a dropdown table showing the ids of the costumers I've added but I see that I can insert in any id number I wish. Why so? Should the costumer field of the model product just restricted to the costumer IDs that I create in the costumer page? and how can I associate the product costumer field just with the costumer's name that I have created?
Hope my question is clear...))
Use
rails generate scaffold product item:string customer:belongs_to
rails generate scaffold does a lot of job for you, but it can't do each and everything for you.
You will have to do manually set other things for yourself. Starting with routes, you have to set them so that you could use something like customers/1/products or customers/2/products. scaffold won't set these routes for you.
resources :customers do
resources :products
end
When you mentioned customer_id while generating scaffold for products, that means a product belongs_to a customer, and you can check it in the code at app/models/product.rb. But now the question is, how the relation goes from a customer to a product. Can a customer have many products, or a customer can have only one product?
In app/models/customer.rb,
class Customer < ActiveRecord::Base
has_one :product # For having only product per customer
# has_many: products # Note that 's' at the end, this makes a customer have as many as products as possible.
end
Similarly, you need to change the view as well as the controller for both fields, and that is a whole lot of process. For that I recommend you to go through the basics of Rails, how do controllers and view work. After that, the stuff would be pretty much easy for you.
Related
I have a Boat Model and its Models such as Brand, Model and Year. I have also User model and I would like to connect them by adding migrations to User model of boat_id and I added belongs_to :boat and has_many :boats to User model. But I can not reach User.first.boat.name from the console even though I am able to reach Boat.first.brand.name.
When I try User.first.boat.name. Console gives an error saying;
NoMethodError: undefined method `boat' for #<User:0x0000000665dc30>
Btw: Boat Model includes model_id brand_id and year_id.
EDIT1:
Or should i remove Boat model and add model_id brand_id and year_id to User model directly.
EDIT2:
I would like to be able to reach User.first.boat.brand.name or User.first.boat.year.nameor User.first.boat.model.name
EDIT3:
Every boat has one brand, year and model. But user can have many boats
EDIT4:
What i will do is;
User can sign up and login
Then User press the link list my boat.
He/she saves the boat then the page renders to User Profile
In the User profile I do not know how to get current user boat name year etc. That is why I am confused. Sorry for the misunderstanding
I think you're confused about how Rails associations work in conjunction with how they are stored in the database. If a User can have many boats, then the foreign key needs to be on the boats table. Currently you have boat_id in the users table, this should be removed and a user_id column needs to be added to the boats table as per Matt's answer.
Reference
To achieve what you're trying to do, you'll need to setup your models in the following manner:
class User
has_many :boats
...
end
class Boat
belongs_to :user # table has a user_id column
...
end
Then you can access a boat's brand using user.boats.first.brand.name
Run rails generate migration, then fill in the change method as follows:
def change
add_column :boats, :user_id, :integer
end
Then run rake db:migrate.
You user model has_many boats, so you need the boats table to refer to users. It's probably worth reading the Rails guide for ActiveRecord associations to get a better feel for how this works: http://guides.rubyonrails.org/association_basics.html#the-has-many-association
I'm making a business administration Rails app.
Is there any info available on how I can enable admin users to add a new field to a table? Behind the scenes this would generate and run the migration and I guess some metaprogramming to include the field in the index, show and _form.html.rb views..
You can't run migrations like that, but you can solve the problem.
The answer is here
403-dynamic-forms
If you con't have a subscription, get one. Railscasts is gold for any rails developer
Basically you make a table in the database for the fields to a model.
For instance
class Product
has_many :product_fields
end
class ProductFields
belongs_to :product
end
I'm new to rails, and I would like to get your help in this issue.
I have two tables Account and Transaction. each transaction shall have from account and to account. so when i add a transaction i shall select from the account table two times to get the FROM and TO accounts (list Selection in new transaction Form).
I'm using scaffold to generate the code and I can add only one relation to the table. Do you how to generate the relation with the account table two times
This is the generation code:
$rails g scaffold account a_name:string a_type:string a_amount:float
$rails g scaffold Transaction account_id:integer account_id:integer t_amount:float t_date:date t_desc:text
You will need two account_id columns in the transactions table, from_account_id and to_account_id, otherwise how will you tell the difference between the two?
rails g scaffold Transaction to_account_id:integer from_account_id:integer
Then, in your Transaction model, you will need to define the relationship properly:
belongs_to :from_account, class_name: 'Account'
belongs_to :to_account, class_name: 'Account'
As a side note, you really should avoid using scaffolding since it makes too many decisions and generalisations for you. You can use individual generators.
rails g model Transaction from_account_id:integer to_account_id:integer
rails g controller transactions
I have a rails application built on top of the Devise cancan bootstrap repo.
I am trying to make a page for employee's to log hours. I set up a scaffold, and it generates a view with the form on that scaffold, but my question is how do I link to that page from the menu, and how can I make it so those logged hours are tied to whichever employee is logged in.
My scaffold is
rails g scaffold hours email:string day:date hours:integer
So besides user creation and authentication Devise has added the following
User model (backed by a users table in the database)
current_user method available in your controller code and in your views
You want to use a foreign_key user_id instead of email in all related models, your scaffold generation would be something like this (I've changed the naming slightly from yours, but you get the idea)
rails g scaffold TimeSheet user_id:integer day:date hours_worked:integer minutes_worked:integer
Then you need to update your User model and the newly created TimeSheet model to create the associations between the two models
See rails guides for more information: http://guides.rubyonrails.org/association_basics.html
class User
# ...
has_many :time_sheets
end
class TimeSheet
belongs_to :user
end
You will need to remove the user_id from the scaffold generated views and set it in the controller during create and update actions
def create
#time_sheet = TimeSheet.new(params[:time_sheet])
#time_sheet.user = current_user
# ....
How can I structure my Rails 3.x application so that the logged-in user can only see records associated with the group he belongs to?
For example,
(Football theme)
Imagine these models:
A Team model, representing each of 30 pro football teams.
A User model, using devise for authentication. Each user has a team_id association.
A Player model, representing each player in the NFL: name:string, team_id:integer.
Each user is a head coach, and should only be able to see his own players in players#index. Rails knows this because the head coach (a User) has a team_id associated with him, as do the players.
Now, with only two controllers (Team, Player) it seems rather easy to manually retype the index and CRUD methods to only display the current_user's associated records.
def index
#players = Player.where(current_user.team_id = ?, 'player.team_id')
end
But imagine you had 6-10 controllers:
Tickets,
Trades,
Employees,
Contracts,
etc.....
(all have a team_id association)
Is there a global way for Rails to only display records associated with the current_user's team?
And...how does Rails prevent users from typing in random id's into a URL to find records unassociated with his team_id. (Imagine a Redskins coach typing in http://www.thesite.com/players/224/edit) and being able to edit a Cowboys player who's player_id = 224.
Thanks.
If all models will have a team_id attribute, you need to define a before filter in your Application Controller along the following lines:
def identify_team
#team = current_user.team
end
In each other controller, you should scope your queries by reference to the team variable e.g.
def index
#players = #team.players.all
end
You could in theory scope through the current_user (current_user.team.players.all) in your controllers but this wouldn't be considered best practice.
Regards
Robin
You can use Associations for this. Each table which ever has the user relationship could have model associations as well in rails.
So through relation current_user.players etc like that you can get.
try having a look at the following railscasts, ryan bates does an excellent job of explaining this stuff. Also checkout teachmetocode website. All these links will give you the foundation in associations and how to setup database associations between different models so you can achieve what you want. these links should get you started:
Self-Referential Association
Polymorphic Association
Two Many-to-Many
HABTM Checkboxes
Embedded Association
ActiveRecord::Relation Walkthrough
Active Record Queries in Rails 3
Many to Many Associations in Ruby on Rails – A Teach Me To Code Tutorial