user2109855
user2109855

Reputation:

How do I populate a model in Rails?

I am fairly new to Rails and I am currently trying to wrap my head around the model/db aspect of the framework. Albeit, I am having some trouble with understanding the connections between models, the database schema, and the views/controller.

For example, lets say that I have an Articles model and the Articles model has_many authors. How do I go about populating the Articles model with actual Articles/content and the Authors model with an array of corresponding Authors?

In other words: If I were to have

articles = Articles.search(params[:search])

in my controller how would the Articles object know to search the actual Articles/content that I have written in the view? I am having trouble understanding that connection.

I hope this makes sense.

Any insights would be appreciated! Thanks.

Upvotes: 1

Views: 808

Answers (1)

poseid
poseid

Reputation: 7156

There are a number of questions hidden in your question, so here are some answers:

  • Article is a class (note, it is singular), that provides class methods to operate on Article data. These class methods could be: Article.new, Article.find (the methods are defined by ActiveRecord). You also can define your own class methods, such as Article.search, which probably gives you an array of Article instances: articles.

  • articles is only visible in the local scope of your controller action. If you use @articles you promote the variable to become an instance variable, that can then be used for rendering of the view. (A view renderer can access controller instance variables)

  • In order to store data from a model in the database, you use the methods that an Article instance inherits from ActiveRecord, such as article.save

  • The whole process of bringing data from a view into the database therefore is: @article = Article.new' defines an empty model that can be loaded from a form in a view. If the form is submitted,@article = Article.create(params[:article])would save the data into the database. And@articles = Article.search(params[:search])` would then give you back an array with objects, that could be rendered in the view.

Some references:

Upvotes: 3

Related Questions