I'm making a versioned JSON API in rails, where the controllers also respond to HTML, meaning it can be accessed as a browser or through an app I'm developing. The controllers have the form Model::V1::UsersController (Model instead of API since they don't just respond to JSON), and I currently have the following in my routes.rb:
namespace :model, path: 'm', as: '' do
# For objects in the model, accessible by JSON (through the app) or HTML (through the browser, using forms to send data to the server).
scope module: 'v1', constraints: OrConstraint.new([APIConstraint.new(1), APIConstraint.new(:default)]) do
resources :users do
collection do
post :sign_in
end
end
end
end
I plan to add more models to my API, but how can I use scaffolding to do this? For example, to create a controller Model::V1::CommentsController, but using the Comment model, instead of Model::V1::Comments.
I've been trying to figure this out for hours, and googling for people with similar problems shows that a few people say not to use scaffolding at all in this case: I don't want to do this, as it would mean writing all the views myself, which would be very time-consuming. Apart from that, I can't find much. nifty-generators was suggested somewhere, but it doesn't seem to be maintained anymore: no activity since 2012. I'm new to rails, and it might be that I've missed something quite obvious, but I find it surprising that not many others have had the same issue.
I've considered making my own generator, but looking at the source of https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb, it seems very complicated.
EDIT: I've just discovered that I can pass the --model-name parameter to the rails scaffold generator to achieve what I want, but for some reason it still tries to create a model with the same name as the controller. How can I change this?
I've settled with this solution, by not generating a model at all using the scaffold generator:
To create Model::V1::CommentsController as the controller and Comments as the model:
rails g model comment
rails g scaffold model/v1/comments --model-name=comment --no-orm
Related
I want to have a link at the bottom of my show.html.erb that links to the new action in a different controller.
class Sample < ActiveRecord::Base
belongs_to :song
end
class Song < ActiveRecord::Base
has_many :samples
end
So, at the bottom of the show action for songs, I want to link to new for samples. This seems pretty easy, but I'm struggling to figure this out. I would also like to pass the id from the song to the form as :song_id
Fiddy, because you're new, let me explain how this works...
Routes
Your problem is that you don't understand the Rails routing structure - I'll hopefully explain it for you.
Rails, since it's an MVC framework, builds a series of "routes" for you. These "routes" are stored in the file available at config/routes.rb.
Routes, as described by the Rails documentation are as follows:
The Rails router recognizes URLs and dispatches them to a controller's
action. It can also generate paths and URLs, avoiding the need to
hardcode strings in your views.
The most important thing you should consider here is the way the routes generate paths for you. These paths are simply Rails "helper" methods, which you can call from your views. The reason these exist is two-fold -
They provide you with a DRY (don't repeat yourself) way of accessing / manipulating data
They are constructed around objects, helping maintain the object-orientated nature of Rails
These will likely mean nothing to you. However, what you need to realize that if set up your routes correctly, it seriously helps your app's infrastructure immensely.
--
Rails
This leads us quite nicely onto appreciating the way in which Rails works
Rails is an MVC (model view controller) framework. This might seem somewhat trivial, but in reality, it's one of the most important aspects to learn about Rails development, and here's why:
The Rails software system works by taking "requests" (user input) and then routing them to specific controller#actions. Those controllers then build model data from the database, and will translate that into either variables or objects, which you can use in your view.
The reason I mention this is that this type of development takes a lot of getting used-to, in that your program's flow is not about logic / functionality, but the accessibility of data. Therefore, when you ask about the routes or other parts of your app, you need to firstly remember what data you wish to show, and also how you want that data to be shown - this will give you the ability to construct & use the routes / controller actions which will get it to work properly
--
Fix
In terms of what you're saying, the way you'd go about achieving the result you want will be to use a nested route:
#config/routes.rb
resources :songs do
resources :samples #-> domain.com/songs/:song_id/samples/new
end
This will create a new route for you (which you can check by firing rake routes in your rails c (console). This will give you a path to use for your samples#new action:
#app/views/songs/show.html.erb
<%= link_to #song.name, new_song_sample_path(#song) %>
The above link will take you to the samples#show action, which you'll be able to populate with as much data as you require from the samples controller. The important thing to note is this action will have params[:song_id] available for you to either build an object from, or otherwise
<%= link_to "New Sample", new_sample_path(:song_id => #song_id) %>
Where #song_id is the variable that has that id in it.
Set paths in link_to tag which you can get by running rake_routes in terminal.
Ex
link_to "New song", new_sample_path(#song)
In the example given above #song is the instance variable of your current page.
You can also get some idea from here:
link_to Base URL Randomly Changed
Song Model:
accepts_nested_attributes_for :sample, allow_destroy: true
Route:
resources :songs do
resources :samples
end
Song's Show file:
<%= link_to "New Sample", new_song_sample_path(#song) %>
in url it will be:
/songs/:song_id/sample/new
Try this and let me know it works or not... I hope this helps you
I'm learning RoR, and I'm getting very confused by the "_path" method as it's used in Controllers and Routes. To be more specific, I'm referring to the many different calls that take the syntax "(something)_path". So far as I know, they all seem to either encode or manipulate a URL or link. I'm having a hard time mastering the use of this type of method because I can't figure out what it's core functionality is supposed to be.
For example, I could use the following code to redirect an old URL structure to a page of listed Tweet instances in my config/routes.rb file:
get '/all' => 'tweets#index', as: 'all_tweets'
Only now can I use the following in an .erb file. Notice the "_path" code at the end of the line.
<%= link_to "All Tweets", all_tweets_path %>
I could also use the following code to create a link to an edit page (and another action) in a different .erb file:
<p><%= link_to tweet.user.name, edit_tweet_path(#tweet) %></p>
I've tried reading through my study materials as well as the RoR documentation, but I always end up more lost than when I began. Does anybody know the low-level definition of this "_path" method?
Helper
It's called a route helper, which means that Rails will generate them to help provide you with resource-based routing structures. I'll explain more in a second
--
To explain properly - Rails is just a framework.
Like all software, it is a series of files loaded in a particular order. As such, Rails creates a series of helper methods in the booting process. These "helper" methods can then be used throughout your application to call functionality / information as you require:
The Rails framework provides a large number of helpers for working
with assets, dates, forms, numbers and model objects, to name a few.
These helpers are available to all templates by default.
In addition to using the standard template helpers provided, creating
custom helpers to extract complicated logic or reusable functionality
is strongly encouraged. By default, each controller will include all
helpers. These helpers are only accessible on the controller through
.helpers
The route helpers (which are generated from your config/routes.rb file give you the ability to call routes which are resourceful. These might seem strange to begin with, but once you understand them, will help you inexorably.
--
Resourceful
To give you more clarity - Rails routes are known as resourceful
This means they are constructed around resources. To give you a brief definition of this, you need to appreciate that the resources of your application are the pools of data you can add to, and pull
from.
To explain further, because Rails is object orientated. If you're new, this won't mean very much, but keep it in mind, as when you progress through the language / work, you'll begin to see why this is important.
Object orientated programming puts OBJECTS at the center of the flow. Typically, you'd put logic at the center, but with OOP, it's the objects. This is very important for us, as it means that everything you do in Rails is based around the objects you can create.
As per the MVC principle (which, again, is what Rails is built on), you'll create / invoke your objects from your Models:
This means that if you want to create a series of routes to "CRUD" (Create Read Update Destroy) your objects, Rails is able to create the routes necessary to do that. This is where the resources directives come from inside the routes file:
Hope this helps!
Actually, these paths are generated based on your routes.rb. If you run this command at your project, you would be able to see all available on your app
rake routes
For example, if I declare my resources in routes.rb like this
resources :posts
then I would automatically have following available paths
posts_path
post_path
new_post_path
edit_post_path
If you use some strange abc_path which has not been declared in routes.rb, then you will get errors.
Hope this is helpful, you will definitely need to work more with Rails and then eventually you will understand all of these things :)
you could find definition for these methods in rails repository:
https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/route_set.rb#L127
I just started trying to get acquainted with Rails, and I don't really know much Ruby. Currently I'm doing a beginners project to get acquainted with the framework which involves a simple form which takes a name, email, and phone number, and when you hit a submit button the page should refresh and present the information you submitted (so there is no database interaction and the model is supposed to do very little). It's very simple, but as my current knowledge of Ruby is pretty minimal, I'm getting somewhat confused. I've written the views for the most part but I'm still confused on what to put in the controller and the model. If anyone could provide any hints that would be great!
You need tableless model. Please refer excellent webcast from Ryan on this topic.
http://railscasts.com/episodes/193-tableless-model
Models (at least those descending from ActiveRecord::Base) require a database, so if you are using a model you are using a database, even if its a simple one like SQLite.
If you don't want to descend into models and generating a migration to create the tables for your models, then you are probably just going to store the form values into instance variables and reference those in your view. Below is a quick example how to do that.
If you have a form that sends data (ex: name and email) to a create action, the create action would look sort of like this:
def create
#name = params[:name]
#email = params[:email]
render :my_template
end
The create action above is assigning the params sent to it to instance variables, which you can then reference in your view. In the above example the create action is going to try and render a view called my_template which would probably be named my_template.html.erb and might look something like this:
<p>Your name is <%= #name => and your email is <%= #email =>.</p>
This is an extremely small and contrived example, but hopefully this helps.
When you move on to working with models your create action might instead create a new instance of a model, pass that model the params sent by the user, save the model, and then redirect them to a page that shows the data.
It is much easier with a database.
rails new stack
cd stack
rm public/index.html
rails generate scaffold Member name:string email:string phone:string
rake db:migrate
rails server
Then browse to localhost:3000/members
(Assuming you are using rails 3)
I created an object named settings. So i also provided its route in the routes.rb file i wrote "map.resources :settings". Now as i'm trying to save to the database with that object, it keeps on getting to the localhost:3000/settings url, which i don't have. i', also having this error
NameError in SettingsController#create
uninitialized constant SettingsController
PLEASE HELP! THANKS!
I am not 100% sure, but I believe you need to have a controller to add a route. Check out this diagram: http://ruby.railstutorial.org/ruby-on-rails-tutorial-book#sec:mvc
If you use Rails, you have to stick to its rules. Rails implements the MVC pattern, where the controller has the role to provide the linking between a request started in the client web page (view) to creating, reading, updating and deleting (CRUD) objects (== models). The routes.rb define here the mapping from the URL to controller actions, not directly to the resources. See the "Rails Guides for Routing" for more information.
If you want to use your model objects, Rails provides an easy way to start that: scaffolding. By using rails generate scaffold setting <attr_name1>:<type1> ..., you are able to create the following:
A migration for the database that creates the settings table.
Generation of the model object Setting that maps to the created database table.
A controller SettingsController that allows CRUD for your model objects.
View files for the actions generated for the controller.
You can all do that by hand, but it is a good starting point to begin with. And read the basic tutorials and play with the example applications to get a feeling for Rails ...
I just started deploying a Rails website. In fact, I started programming on Rails 2 days ago.
I've created a new project, added some gems, etc. Everything is working properly, and I have some basic knowledge on how all works.
The thing is that what I want to create is a simple website with some sections (let's say, News, Contact, About, Products...). All this content is kinda static.
But I came in a problem. I don't really know what to do in order to create them. What I want, for example, is something like mypage.com/products/fashionableproduct, mypage.com/about, etc, or even mypage.com/page/products.
I thought about creating a Controller, then an action for each page... afterwards, I came up with other solution: scaffolding. Creating a resource called page, that has a title, etc...
I'm really a beginner on this topic, and I would like to hear your helpful voice.
Thanks!
Check out https://github.com/thoughtbot/high_voltage for static pages for Rails.
And check out http://railscasts.com/episodes/30-pretty-page-title for setting page titles.
The paths to your files are determined by your routes. The configuration file for routes is located at config/routes.rb. You can match a URL path, and then point to a given resource. More information about routes here: http://guides.rubyonrails.org/routing.html
If you generate a controller, you can process any dynamic data and then pass this data to these "kinda static" pages. Here is an example configuration that would match the path "mypage.com/about" and display the appropriate page:
# config/routes.rb
match "/about" => "example_controller#about"
# app/controllers/example_controller.rb
class ExampleController < ApplicationController
def about
# calculations
end
end
# app/views/example/about.html.erb
<!-- This is your HTML page -->
I think the title of your post might be a bit misleading. I have the feeling you don't want static pages but some database stored content. Just like Ben Simpson tells you to do, create a normal pages controller and make it work.
In the end you might want to customize some routes to get them to be exactly the way you want as in your examples.
Since you just started the app, I strongly recommend you start over and make a new app with Rails 3.1 which is the most current version and learn how to do the basics through http://guides.rubyonrails.org/ and a few other sources such as http://railscasts.com.
You will then learn Rails the right way from the beginning. Good luck and have fun in the process.