Search Results

Search found 15231 results on 610 pages for 'presentation model'.

Page 78/610 | < Previous Page | 74 75 76 77 78 79 80 81 82 83 84 85  | Next Page >

  • Ruby on Rails has_one Model Not Supplying ID Column

    - by Metric Scantlings
    I have a legacy rails (version 1.2.3) app which runs without issue on a number of servers (not to mention my local environment). Deployed to its newest server, though, and I now get ActiveRecord::StatementInvalid: Mysql::Error: #23000Column 'video_id' cannot be null errors. Below are the models/relationships, simplified: class Video < ActiveRecord::Base has_one(:user, :dependent => :destroy) end class User < ActiveRecord::Base belongs_to(:video) end And below is a rails console transcript of the relationships failing: >> video = Video.create(:title => 'New Video') => #<Video:0xb6d5e31c>... >> video.id => 5 >> video.user = User.create(:name => 'Tester') ActiveRecord::StatementInvalid: Mysql::Error: #23000Column 'video_id' cannot be null: INSERT INTO users (`name`, `video_id`) VALUES('Tester', NULL) from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/connection_adapters/abstract_adapter.rb:128:in `log' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/connection_adapters/mysql_adapter.rb:243:in `execute' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/connection_adapters/mysql_adapter.rb:253:in `insert' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1811:in `create_without_callbacks' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/callbacks.rb:254:in `create_without_timestamps' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/timestamp.rb:39:in `create' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1789:in `create_or_update_without_callbacks' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/callbacks.rb:242:in `create_or_update' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1545:in `save_without_validation' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/validations.rb:752:in `save_without_transactions' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:129:in `save' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/connection_adapters/abstract/database_statements.rb:59:in `transaction' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:95:in `transaction' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:121:in `transaction' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:129:in `save' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:451:in `create' from (irb):3 from :0 Has anyone else come across ActiveRecord not sending an ID when it clearly knows it?

    Read the article

  • No-Model Formtastic Form

    - by Kevin Sylvestre
    I am looking to reproduce the following with Formtastic: <% form_tag '/search', :method => 'get' do %> <%= text_field_tag :q, params[:q] %> <% end %> So far I have: <% semantic_form_for :search, :html => { :method => :get } do |form| %> <% form.inputs do %> <%= form.input :q %> <% end %> <% end %> However, this requires access to the parameter hash using: params[:search][:q] Instead of my required: params[:q] I'd like to use Formtastic for all forms in the application I am working on, and so far I have only had problems with this one. Any ideas?

    Read the article

  • How to add and remove nested model fields dynamically using Haml and Formtastic

    - by Brightbyte8
    We've all seen the brilliant complex forms railscast where Ryan Bates explains how to dynamically add or remove nested objects within the parent object form using Javascript. Has anyone got any ideas about how these methods need to be modified so as to work with Haml Formtastic? To add some context here's a simplified version of the problem I'm currently facing: # Teacher form (which has nested subject forms) [from my application] - semantic_form_for(@teacher) do |form| - form.inputs do = form.input :first_name = form.input :surname = form.input :city = render 'subject_fields', :form => form = link_to_add_fields "Add Subject", form, :subjects # Individual Subject form partial [from my application] - form.fields_for :subjects do |ff| #subject_field = ff.input :name = ff.input :exam = ff.input :level = ff.hidden_field :_destroy = link_to_remove_fields "Remove Subject", ff # Application Helper (straight from Railscasts) def link_to_remove_fields(name, f) f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)") end def link_to_add_fields(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)} \")")) end #Application.js (straight from Railscasts) function remove_fields(link) { $(link).previous("input[type=hidden]").value = "1"; $(link).up(".fields").hide(); } function add_fields(link, association, content) { var new_id = new Date().getTime(); var regexp = new RegExp("new_" + association, "g") $(link).up().insert({ before: content.replace(regexp, new_id) }); } The problem with implementation seems to be with the javascript methods - the DOM tree of a Formtastic form differs greatly from a regular rails form. I've seen this question asked online a few times but haven't come across an answer yet - now you know that help will be appreciated by more than just me! Jack

    Read the article

  • The subscription model behind CSS selectors?

    - by Martin Kristiansen
    With CSS selectors a query string body > h1.span subscribes to a specific type of nodes in the tree. Does anyone know how this is done? Selectors for transformations, how does the browser select the result set? And is there a trick to making it efficient? I imagine there being some sort of hierarchical type-tree for the entire structure to which the nodes subscribe and which is what is used when doing the selector queries — but this is only a guess. Does anyone know the real answer? Or even more interesting, what would be the best way to do dynamic lookups on a tree based on jQuery/CSS search queries?

    Read the article

  • ASP.NET MVC Model Binding

    - by Noel
    If i have a Controller Action that may recieve both HTTP GET and HTTP POST from a number of different sources with each source sending different data e.g. Source1 performs a form POST with two form items Item1 and Item2 Source2 performs a GET where the data is contained in the query string (?ItemX=2&ItemY=3) Is it possible to have a controller action that will cater for all these cases and perform binding automatically e.g. public ActionResult Test(Dictionary data) { // Do work ... return View(); } Is this possible with a custom binder or some other way? Dont want to work directly with HttpContext.Request if possible

    Read the article

  • Find which alias method is called in rails model

    - by Kashif Umair Liaqat
    I am new to rails development. I have created some aliases to a method and I want to know that which alias is called. I have this code. alias_method :net_stock_quantity_equals :net_stock_quantity alias_method :net_stock_quantity_gte :net_stock_quantity alias_method :net_stock_quantity_lte :net_stock_quantity alias_method :net_stock_quantity_gt :net_stock_quantity alias_method :net_stock_quantity_lt :net_stock_quantity def net_stock_quantity #some code here end I want to know that user has called which alias. Like if user calls net_stock_quantity_equals then I should know that the user has called net_stock_quantity_equals not net_stock_quantity. Any help would be appreciated.

    Read the article

  • How to avoid saving a blank model which attributes can be blank

    - by auralbee
    Hello people, I have two models with a HABTM association, let´s say book and author. class Book has_and_belongs_to_many :authors end class Author has_and_belongs_to_many :books end The author has a set of attributes (e.g. first-name,last-name,age) that can all be blank (see validation). validates_length_of :first_name, :maximum => 255, :allow_blank => true, :allow_nil => false In the books_controller, I do the following to append all authors to a book in one step: @book = Book.new(params[:book]) @book.authors.build(params[:book][:authors].values) My question: What would be the easiest way to avoid the saving of authors which fields are all blank to prevent too much "noise" in the database? At the moment, I do the following: validate :must_have_some_data def must_have_some_data empty = true hash = self.attributes hash.delete("created_at") hash.delete("updated_at") hash.each_value do |value| empty = false if value.present? end if (empty) errors.add_to_base("Fields do not contain any data.") end end Maybe there is an more elegant, Rails-like way to do that. Thanks.

    Read the article

  • WPF Prism MVVM, Internationalized Wizard Passing model data between the wizard steps

    - by Nick V
    I've found the following example of a wizard located here: http://www.codeproject.com/Articles/31837/Creating-an-Internationalized-Wizard-in-WPF Now I've spent quite some time looking at the example and i understand pretty much everything. But i can't figure out how he passes an object between the different modelViews. And as you can imagine that step is quite crucial.. In the example he uses an CupOfCoffee Object in the main wizardviewmodel and somehow manages to adjust it throughout the wizard. But i cant see anywhere how he does that. I've already tried to recreate a project like he has but no success. Could anyone tell me how he passes the objects between the different viewModels?

    Read the article

  • ASP.NET MVC: null reference exception using HtmlHelper.TextBox and custom model binder

    - by mr.nicksta
    I have written a class which implements IModelBinder (see below). This class handles a form which has 3 inputs each representing parts of a date value (day, month, year). I have also written a corresponding HtmlHelper extension method to print out three fields on the form. When the day, month, year inputs are given values which can be parsed, but a seperate value fails validation, all is fine - the fields are repopulated and the page served to the user as expected. however when an invalid values are supplied and a DateTime cannot be parsed, i return an arbitrary DateTime so that the fields will be repopulated when returned to the user. I read up on similar problems people have had and they all seemed to be due to lack of calling SetModelValue(). I wasn't doing this, but even after adding the problem has not been resolved. public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { string modelName = bindingContext.ModelName; string monthKey = modelName + ".Month"; string dayKey = modelName + ".Day"; string yearKey = modelName + ".Year"; //get values submitted on form string year = bindingContext.ValueProvider[yearKey].AttemptedValue; string month = bindingContext.ValueProvider[monthKey].AttemptedValue; string day = bindingContext.ValueProvider[dayKey].AttemptedValue; DateTime parsedDate; if (DateTime.TryParse(string.Format(DateFormat, year, month, day), out parsedDate)) return parsedDate; //could not parse date time report error, return current date bindingContext.ModelState.AddModelError(yearKey, ValidationErrorMessages.DateInvalid); //added this after reading similar problems, does not fix! bindingContext.ModelState.SetModelValue(modelName, bindingContext.ValueProvider[modelName]); return DateTime.Today; } the null reference exception is thrown when i attempt to create a textbox for the Year property of the date, but strangely not for Day or Month! Can anyone offer an explanation as to why this is? Thanks :-)

    Read the article

  • Documentation for the Excel object model.

    - by mcoolbeth
    The documentation for .NET's Excel interop API at msdn.com seems rather sparse. Does anyone know of more thorough documentation elsewhere on the web? I am looking for something that would, for example, list and explain all the properties of a Worksheet object. Thanks.

    Read the article

  • point light illumination using Phong model

    - by Myx
    Hello: I wish to render a scene that contains one box and a point light source using the Phong illumination scheme. The following are the relevant code snippets for my calculation: R3Rgb Phong(R3Scene *scene, R3Ray *ray, R3Intersection *intersection) { R3Rgb radiance; if(intersection->hit == 0) { radiance = scene->background; return radiance; } ... // obtain ambient term ... // this is zero for my test // obtain emissive term ... // this is also zero for my test // for each light in the scene, obtain calculate the diffuse and specular terms R3Rgb intensity_diffuse(0,0,0,1); R3Rgb intensity_specular(0,0,0,1); for(unsigned int i = 0; i < scene->lights.size(); i++) { R3Light *light = scene->Light(i); R3Rgb light_color = LightIntensity(scene->Light(i), intersection->position); R3Vector light_vector = -LightDirection(scene->Light(i), intersection->position); // check if the light is "behind" the surface normal if(normal.Dot(light_vector)<=0) continue; // calculate diffuse reflection if(!Kd.IsBlack()) intensity_diffuse += Kd*normal.Dot(light_vector)*light_color; if(Ks.IsBlack()) continue; // calculate specular reflection ... // this I believe to be irrelevant for the particular test I'm doing } radiance = intensity_diffuse; return radiance; } R3Rgb LightIntensity(R3Light *light, R3Point position) { R3Rgb light_intensity; double distance; double denominator; if(light->type != R3_DIRECTIONAL_LIGHT) { distance = (position-light->position).Length(); denominator = light->constant_attenuation + (light->linear_attenuation*distance) + (light->quadratic_attenuation*distance*distance); } switch(light->type) { ... case R3_POINT_LIGHT: light_intensity = light->color/denominator; break; ... } return light_intensity; } R3Vector LightDirection(R3Light *light, R3Point position) { R3Vector light_direction; switch(light->type) { ... case R3_POINT_LIGHT: light_direction = position - light->position; break; ... } light_direction.Normalize(); return light_direction; } I believe that the error must be somewhere in either LightDirection(...) or LightIntensity(...) functions because when I run my code using a directional light source, I obtain the desired rendered image (thus this leads me to believe that the Phong illumination equation is correct). Also, in Phong(...), when I computed the intensity_diffuse and while debugging, I divided light_color by 10, I was obtaining a resulting image that looked more like what I need. Am I calculating the light_color correctly? Thanks.

    Read the article

  • rails inverting to_xml and getting the original model

    - by djacobs7
    I did this: [User.first, User.last].to_xml and got this: <users type="array"> <user> <created-at type="datetime">2010-03-16T06:40:51Z</created-at> <id type="integer">3</id> <password-hash></password-hash> <salt></salt> <updated-at type="datetime">2010-03-16T06:40:51Z</updated-at> <username nil="true"></username> </user> <user> <created-at type="datetime">2010-03-23T03:58:15Z</created-at> <id type="integer">7</id> <password-hash></password-hash> <salt></salt> <tutorial-state nil="true"></tutorial-state> <updated-at type="datetime">2010-03-23T03:58:15Z</updated-at> <username nil="true"></username> </user> </users> How can I take that string of xml and invert it to get the original activerecord objects back?

    Read the article

  • Bad Practice requiring file within a model?

    - by Lee Marshall
    I have built an MVC php application and was wondering, if instead of having to write out a large amount of html and set the data, could I not just have all this html (with some php) in a separate file and just require it? For example: $test = '<div> Test content <div>More content</div> </div>'; $APP->Template->setData('test', $test, FALSE); Instead could I not just use: $test = require("includes/content.php"); $APP->Template->setData('test', $test, FALSE); Would this be considered as bad practise? It just seems that by requiring files, it can shorten the length of controllers. Would be good to get anybodies advice on this matter.

    Read the article

  • How to model "target day" in UML Classdiagrams

    - by Tobiask
    Hi there, I want to describe the following situation in an UML Classdiagram: A day, on which a newspaper is send to a customer. This day could be sth. like "every friday" or "every first day of a month". My idea to represent this in a UML Classdiagram: -targetDay:Integer -targetDayGrid:Enumeration targetDay would be sth. like "1" (for monday) oder "5" (for friday) or it could be "1" for the first day of the month or "10" for the 10th day of the month. targetDayGrid is an enum: weekly, monthly. So the enum sets the semantic meaning of the number in targetDay. I´m not happy with this, do you know any other solution to represent my problem? Or do you think my solution is okay?

    Read the article

  • ASP.NET MVC Model Binding into a List

    - by Maxim Z.
    In my ASP.NET MVC site, part of a feature allows the user to enter the hours when a certain venue is open. I've decided to store these hours in a VenueHours table in my database, with a FK-to-PK relationship to a Venues table, as well as DayOfWeek, OpeningTime, and ClosingTime parameters. In my View, I want to allow the user to only input the times they know about; in other words, some days may not be filled in for a Venue. I'm thinking of creating checkboxes that the user can check to enable the OpeningTime and ClosingTime fields for the DayOfWeek that the checkbox belongs to. My question relates to how to pass this information to my HttpPost Controller Action. As I know the maximum amount of Days that can be passed in (7), I could of course just write 7 nullable VenueHour parameters into my Action, but I'm sure there's a better way. Can I somehow bind the View information into a List that is passed to my Action? This will also help me if I run into a scenario where there is no limit to how much information the user can fill in.

    Read the article

  • Tying in to Django Admin's Model History

    - by akdom
    The Setup: I'm working on a Django application which allows users to create an object in the database and then go back and edit it as much as they desire. Django's admin site keeps a history of the changes made to objects through the admin site. The Question: How do I hook my application in to the admin site's change history so that I can see the history of changes users make to their "content" ?

    Read the article

  • ORM model and DAO in my particular case

    - by EugeneP
    I have the DB structure as follows: table STUDENT (say, id, surname, etc) table STUDENT_PROPERTIES (say, name_of_the_property:char, value_of_the_property:char, student_id:FK) table COURSE (id, name, statusofcourse_id) table STATUSOFCOURSE (id, name_of_status:char ('active','inactive','suspended' etc)) table STUDENT_COURSE (student_id,course_id,statusofcourse_id) Let's try to pick up domain objects in my database: Student and Course are main entities. Student has a list of courses he attends, also he has a list of properties, that is all for this student. Next, Course entitity. It may contain a list of students that attend it. But in fact, the whole structure looks like this: the starting point is Student, with it's PK we can look a list of his properties, then we look into the STUDENT_COURSE and extract both FK of the Course entity and also the Status of the combination, it would look like "Student named bla bla, with all his properties, attends math and the status of it is "ACTIVE". now, quotation 1) Each DAO instance is responsible for one primary domain object or entity. If a domain object has an independent lifecycle, it should have its own DAO. 2) The DAO is responsible for creations, reads (by primary key), updates, and deletions -- that is, CRUD -- on the domain object. Now, first question is What are entities in my case? Student, Course, Student_Course, Status = all except for StudentProperties? Do I have to create a separate DAO for every object?

    Read the article

  • Asp.Net MVC 2: How exactly does a view model bind back to the model upon post back?

    - by Dr. Zim
    Sorry for the length, but a picture is worth 1000 words: In ASP.NET MVC 2, the input form field "name" attribute must contain exactly the syntax below that you would use to reference the object in C# in order to bind it back to the object upon post back. That said, if you have an object like the following where it contains multiple Orders having multiple OrderLines, the names would look and work well like this (case sensitive): This works: Order[0].id Order[0].orderDate Order[0].Customer.name Order[0].Customer.Address Order[0].OrderLine[0].itemID // first order line Order[0].OrderLine[0].description Order[0].OrderLine[0].qty Order[0].OrderLine[0].price Order[0].OrderLine[1].itemID // second order line, same names Order[0].OrderLine[1].description Order[0].OrderLine[1].qty Order[0].OrderLine[1].price However we want to add order lines and remove order lines at the client browser. Apparently, the indexes must start at zero and contain every consecutive index number to N. The black belt ninja Phil Haack's blog entry here explains how to remove the [0] index, have duplicate names, and let MVC auto-enumerate duplicate names with the [0] notation. However, I have failed to get this to bind back using a nested object: This fails: Order.id // Duplicate names should enumerate at 0 .. N Order.orderDate Order.Customer.name Order.Customer.Address Order.OrderLine.itemID // And likewise for nested properties? Order.OrderLine.description Order.OrderLine.qty Order.OrderLine.price Order.OrderLine.itemID Order.OrderLine.description Order.OrderLine.qty Order.OrderLine.price I haven't found any advice out there yet that describes how this works for binding back nested ViewModels on post. Any links to existing code examples or strict examples on the exact names necessary to do nested binding with ILists? Steve Sanderson has code that does this sort of thing here, but we cannot seem to get this to bind back to nested objects. Anything not having the [0]..[n] AND being consecutive in numbering simply drops off of the return object. Any ideas?

    Read the article

  • Weak event handler model for use with lambdas

    - by Benjol
    OK, so this is more of an answer than a question, but after asking this question, and pulling together the various bits from Dustin Campbell, Egor, and also one last tip from the 'IObservable/Rx/Reactive framework', I think I've worked out a workable solution for this particular problem. It may be completely superseded by IObservable/Rx/Reactive framework, but only experience will show that. I've deliberately created a new question, to give me space to explain how I got to this solution, as it may not be immediately obvious. There are many related questions, most telling you you can't use inline lambdas if you want to be able to detach them later: Weak events in .Net? Unhooking events with lambdas in C# Can using lambdas as event handlers cause a memory leak? How to unsubscribe from an event which uses a lambda expression? Unsubscribe anonymous method in C# And it is true that if YOU want to be able to detach them later, you need to keep a reference to your lambda. However, if you just want the event handler to detach itself when your subscriber falls out of scope, this answer is for you.

    Read the article

  • How to get child container reference in View Model

    - by niels-verkaart
    Hello, I´m trying to share a Data Service (Entity Manager) wrapped in a Repository from a ViewModel (called 'AVM') in Module A to a ViewModel (called 'BVM') in Module B, and I can't get this working. We use PRISM/Unity 2.0 This is my scenario: A user may open multiple Customer screens (composite view as mini shell) each with another customer (unit of work). We realize this using child containers. Each child container resolves it's own repository with its own Entity manager (the repository is a singleton within the child container). This is done in module A. The main shell has a main region manager, and each Customer screen with its childcontainer creates a scoped region. In each customer screen there is a View 'AV' (connected to ViewModel 'AVM') with a SubRegion (tab control) registered as 'SubRegion'. We create this with a 'Screen Factory' In Module B we have a Customer Orders in View 'BV' and ViewModel 'BVM'. In the constructor of Module B we get the main container by injection. In the initialize method we resolve the (main) region manager and register View 'BV' with it. In the constructor of View 'BV' a ViewModel 'BVM' is injected/created. Now this works, but the ViewModel 'BVM' cannot get the child container. It only get the main container. Is this doable, or do I have to do this another way? Thanks, Niels

    Read the article

  • Why can't Doctrine retrieve my model data?

    - by scottm
    So, I'm trying to use Doctrine to retrieve some data. I have some basic code like this: $conn = Doctrine_Manager::connection(CONNECTION_STRING); $site = Doctrine_Core::getTable('Site')->find('00024'); echo $site->SiteName; However, this keeps throwing a SQL error that 'column siteid does not exist'. When I look at the exception the SQL query is this (you can see the error is that the inner_tbl alias for siteid is set to s__siteid, so querying inner_tabl.siteid is what's broken): SELECT TOP 1 [inner_tbl].[siteid] AS [s__siteid] FROM (SELECT TOP 1 [s].[siteid] AS [s__siteid], [s].[name] AS [s__name], [s].[address] AS [s__address], [s].[city] AS [s__city], [s].[zip] AS [s__zip], [s].[state] AS [s__state], [s].[region] AS [s__region], [s].[callprocessor] AS [s__callprocessor], [s].[active] AS [s__active], [s].[dateadded] AS [s__dateadded] FROM [Sites] [s] WHERE ([s].[siteid] = '00024') ) AS [inner_tbl] Why is the query being generated this way? Could it be the way the Yaml schema is laid out? Site: connection: 0 tableName: Sites columns: siteid: type: string(5) fixed: true unsigned: false primary: true autoincrement: false name: type: string(300) fixed: false unsigned: false notnull: true primary: false autoincrement: false address: type: string(100) fixed: false unsigned: false notnull: false primary: false autoincrement: false city: type: string(100) fixed: false unsigned: false notnull: false primary: false autoincrement: false zip: type: string(5) fixed: false unsigned: false notnull: false primary: false autoincrement: false state: type: string(2) fixed: true unsigned: false notnull: true primary: false autoincrement: false region: type: integer(4) fixed: false unsigned: false notnull: true default: (5) primary: false autoincrement: false callprocessor: type: integer(4) fixed: false unsigned: false notnull: true primary: false autoincrement: false active: type: integer(1) fixed: false unsigned: false notnull: true primary: false autoincrement: false dateadded: type: timestamp(16) fixed: false unsigned: false notnull: true default: (getdate()) primary: false autoincrement: false

    Read the article

  • RSpec mocking a nested model in Rails - ActionController problem

    - by emson
    Hi All I am having a problem in RSpec when my mock object is asked for a URL by the ActionController. The URL is a Mock one and not a correct resource URL. I am running RSpec 1.3.0 and Rails 2.3.5 Basically I have two models. Where a subject has many notes. class Subject < ActiveRecord::Base validates_presence_of :title has_many :notes end class Note < ActiveRecord::Base validates_presence_of :title belongs_to :subject end My routes.rb file nests these two resources as such: ActionController::Routing::Routes.draw do |map| map.resources :subjects, :has_many => :notes end The NotesController.rb file looks like this: class NotesController < ApplicationController # POST /notes # POST /notes.xml def create @subject = Subject.find(params[:subject_id]) @note = @subject.notes.create!(params[:note]) respond_to do |format| format.html { redirect_to(@subject) } end end end Finally this is my RSpec spec which should simply post my mocked objects to the NotesController and be executed... which it does: it "should create note and redirect to subject without javascript" do # usual rails controller test setup here subject = mock(Subject) Subject.stub(:find).and_return(subject) notes_proxy = mock('association proxy', { "create!" => Note.new }) subject.stub(:notes).and_return(notes_proxy) post :create, :subject_id => subject, :note => { :title => 'note title', :body => 'note body' } end The problem is that when the RSpec post method is called. The NotesController correctly handles the Mock Subject object, and create! the new Note object. However when the NoteController#Create method tries to redirect_to I get the following error: NoMethodError in 'NotesController should create note and redirect to subject without javascript' undefined method `spec_mocks_mock_url' for #<NotesController:0x1034495b8> Now this is caused by a bit of Rails trickery that passes an ActiveRecord object (@subject, in our case, which isn't ActiveRecord but a Mock object), eventually to url_for who passes all the options to the Rails' Routing, which then determines the URL. My question is how can I mock Subject so that the correct options are passed so that I my test passes. I've tried passing in :controller = 'subjects' options but no joy. Is there some other way of doing this? Thanks...

    Read the article

  • Table Design For SystemSettings, Best Model

    - by Chris L
    Someone suggested moving a table full of settings, where each column is a setting name(or type) and the rows are the customers & their respective settings for each setting. ID | IsAdmin | ImagePath ------------------------------ 12 | 1          | \path\to\images 34 | 0          | \path\to\images The downside to this is every time we want a new setting name(or type) we alter the table(via sql) and add the new (column)setting name/type. Then update the rows(so that each customer now has a value for that setting). The new table design proposal. The proposal is to have a column for setting name and another column for setting. ID | SettingName | SettingValue ---------------------------- 12 | IsAdmin        | 1 12 | ImagePath   | \path\to\images 34 | IsAdmin        | 0 34 | ImagePath   | \path\to\images The point they made was that adding a new setting was as easy as a simple insert statement to the row, no added column. But something doesn't feel right about the second design, it looks bad, but I can't come up with any arguments against it. Am I wrong?

    Read the article

  • Access current_user in model

    - by LearnRails
    I have 3 tables items (columns are: name , type) history(columns are: date, username, item_id) user(username, password) When a user say "ABC" logs in and creates a new item, a history record gets created with the following after_create filter. How to assign this username ‘ABC’ to the username field in history table through this filter. class Item < ActiveRecord::Base has_many :histories after_create :update_history def update_history histories.create(:date=Time.now, username= ?) end My login method in session_controller def login if request.post? user=User.authenticate(params[:username]) if user session[:user_id] =user.id redirect_to( :action='home') flash[:message] = "Successfully logged in " else flash[:notice] = "Incorrect user/password combination" redirect_to(:action="login") end end end I am not using any authentication plugin. I would appreciate if someone could tell me how to achieve this without using plugin(like userstamp etc.) if possible.

    Read the article

< Previous Page | 74 75 76 77 78 79 80 81 82 83 84 85  | Next Page >